Image for post
Image for post

Export your widget to image with flutter

Parth Jansari
Sep 13, 2018 · 2 min read

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.

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).

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.

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 week i’ll back with another blog on ScopedModel. Be sure to mention all the awesome things you do with flutter.

Flutter Community

Articles and Stories from the Flutter Community

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

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