Export your widget to image with flutter

Parth Jansari
Flutter Community
Published in
2 min readSep 13, 2018

--

Some days ago I was messing around with flutter and thought that everything in flutter is rendered pixel by pixel so there must be a way to export rendered things to bytes and then uses it to store to file or share via converting to base64 string. The obvious way is to use canvas and export rendered image data. Another way is to use the RepaintBoundary widget then use its ‘toImage’ method to capture an image for the current state of the widget

How to do that in your app?

Let’s see how to do it. first, you declare a global key.then we assign it to our RepaintBoundary. Inside our RepaintBoundary, we will pass the widget that needs to be converted to image.after that we create a function called capturePng which will resolve a future of type Future<Uint8List>.

Inside it, we create a RenderRepaintBoundary object and assign it RenderObject via currentContext.

RenderRepaintBoundary boundary = _globalKey.currentContext.findRenderObject();

After that, we obtain the image via toImage() Method of the RenderRepaintBoundary object.

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

ui.Image image = await boundary.toImage(pixelRatio: 3.0);

After getting raw image data we convert it to bytecode and after that, we convert the bytecode to Unit8List which we can use to get a base64 string.

ByteData byteData =await image.toByteData(format: ui.ImageByteFormat.png);Uint8List pngBytes = byteData.buffer.asUint8List();String bs64 = base64Encode(pngBytes);

After getting the image you can use the data however you like. hear is a complete main.dart to test the code directly or you can clone the GitHub repo from below-given link

https://github.com/parth181195/flutter_widget_to_image

That's all for today.next week i’ll back with another blog on ScopedModel. Be sure to mention all the awesome things you do with flutter.

--

--