captureImage method

Future<Uint8List?> captureImage([
  1. Color? backgroundColor
])

Captures the image from the current widget. This will return null if the image cannot be captured for any reason.

This will always return null on the Web platform.

This accepts an optional backgroundColor. When set, the backgroundColor will be painted on the image first and then the widget image will be painted. This can be useful when widgets inherit a background from their parent because that background would not be part of the captured value.

Implementation

Future<Uint8List?> captureImage([
  Color? backgroundColor,
]) async {
  var boundary = _renderKey!.currentContext!.findRenderObject()
      as RenderRepaintBoundary?;
  Uint8List? image;
  if (!kIsWeb) {
    if (!kDebugMode || boundary?.debugNeedsPaint != true) {
      _backgroundColor = backgroundColor;
      if (mounted == true) {
        setState(() {});
      }

      await Future.delayed(Duration(milliseconds: 500));
      boundary = _renderKey!.currentContext!.findRenderObject()
          as RenderRepaintBoundary?;
      var img = await boundary!.toImage(
        pixelRatio: MediaQuery.of(context).devicePixelRatio,
      );
      var byteData = await img.toByteData(
        format: ui.ImageByteFormat.png,
      );
      image = byteData?.buffer.asUint8List();
      _backgroundColor = null;
      if (mounted == true) {
        setState(() {});
      }
    }
  }

  return image;
}