Flutter Community
Published in

Flutter Community

Export your widget to image with flutter

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


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.



Articles and Stories from the Flutter Community

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store