toImageSync method

Image toImageSync({
  1. double pixelRatio = 1.0,
})

Capture an image of the current state of this render object and its children synchronously.

The returned ui.Image has uncompressed raw RGBA bytes in the dimensions of the render object, multiplied by the pixelRatio.

To use toImageSync, the render object must have gone through the paint phase (i.e. debugNeedsPaint must be false).

The pixelRatio describes the scale between the logical pixels and the size of the output image. It is independent of the dart:ui.FlutterView.devicePixelRatio for the device, so specifying 1.0 (the default) will give you a 1:1 mapping between logical pixels and the output pixels in the image.

This API functions like toImage, except that rasterization begins eagerly on the raster thread and the image is returned before this is completed.

The following is an example of how to go from a GlobalKey on a RepaintBoundary to an image handle:
link
class ImageCaptureHome extends StatefulWidget {
  const ImageCaptureHome({super.key});

  @override
  State<ImageCaptureHome> createState() => _ImageCaptureHomeState();
}

class _ImageCaptureHomeState extends State<ImageCaptureHome> {
  GlobalKey globalKey = GlobalKey();

  void _captureImage() {
    final RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject()! as RenderRepaintBoundary;
    final ui.Image image = boundary.toImageSync();
    print('Image dimensions: ${image.width}x${image.height}');
  }

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      key: globalKey,
      child: Center(
        child: TextButton(
          onPressed: _captureImage,
          child: const Text('Hello World', textDirection: TextDirection.ltr),
        ),
      ),
    );
  }
}

See also:

Implementation

ui.Image toImageSync({ double pixelRatio = 1.0 }) {
  assert(!debugNeedsPaint);
  final OffsetLayer offsetLayer = layer! as OffsetLayer;
  return offsetLayer.toImageSync(Offset.zero & size, pixelRatio: pixelRatio);
}