Download a widget as image in flutter
Introduction
screenshot is an image that shows specific portion of your computer or phone. every modern device come with screenshot feature. using flutter use can capture specific part of your UI and convert it to an image.
using flutter you can achieve this by using following classes:
Image:
from dart ui library
File:
from dart io library
GallerySaver:
from a package called gallery_saver
Directory:
from path_provider package
lastly , the most important widget , which is RenderRepaintBoundary
This widget creates a separate display list for its child, which can improve performance if the subtree repaints at different times than the surrounding parts of the tree.
firstly , create a key for RepaintBoundary widget
var _repaintKey =GlobalKey();
then wrap a widget that you want to download as picture with RepaintBoundary widget.
RepaintBoundary(
key: _repaintKey,
child: someWidget()
)
then implement download function:
_downloadImage()async{
RenderRepaintBoundary boundary =
_repaintKey.currentContext.findRenderObject(); // get render object
ui.Image image = await boundary.toImage(); //convert to image
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
final String path =await AppPathProvider.createFolderInAppDocDir("screenshots");
final imagePath = await File('${AppPathProvider.path}/${DateTime.now().millisecondsSinceEpoch.toString()+".png"}')
.writeAsBytes(pngBytes ,flush: true);
var newFile=await imagePath.create(recursive: true);
GallerySaver.saveImage(newFile.path).then(( path) { // save to gallery
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(
'Image Saved'
), backgroundColor: Colors.green));
});
log('SAVED');
log(newFile.uri.path);
//show alert saved
}
that’s it:)