How to convert a widget to an image in Flutter

At times, we want to take app screenshots to use as marketing material. Or, we may want to capture a particular widget layout to get feedback from our peers. In these cases, we can use Flutter’s widget-to-image conversion feature to generate high-quality images from the widgets directly. Let’s see how it works!

First, wrap the widget that we want to capture with a RepaintBoundary:

RepaintBoundary(
child: WidgetToBeCaptured(),
)

Next, provide it with a GlobalKey:

final GlobalKey globalKey = GlobalKey();
RepaintBoundary(
key: globalKey,
child: WidgetToBeCaptured(),
)

Providing a global key is important since it is used to retrieve the widget boundary while converting it to an image.

Finally, we write the method to convert the widget to an image and get its bytes.

Future<Uint8List> captureWidget() async {}

Steps

Let’s write and understand the function step-by-step.

Step 1: Access RenderRepaintBoundary from the global key using the findRenderObject method.

final RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject();

Step 2: Convert the boundary to an image using the toImage method.

final ui.Image image = await boundary.toImage();

Step 3: Convert the image to PNG byte data via the toByteData method.

final ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);

Step 4: Retrieve bytes from the byte data, like this:

final Uint8List pngBytes = byteData.buffer.asUint8List();

That’s it! Here’s what the complete function looks like:

Future<Uint8List> captureWidget() async {
final RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject();
final ui.Image image = await boundary.toImage();
final ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
final Uint8List pngBytes = byteData.buffer.asUint8List();
return pngBytes;
}

Now, call the function at any time to convert the widget to an image, and use the retrieved bytes to display the image.