I want to download widgets screenshots as an image file in flutter Web. Is there any to do this? By the way for converting the widget to Uint8List, I am using the screenshot plugin.
You can use the RenderRepaintBoundary.toImage() function to convert the widget into an image. Then you convert to byteData, then to Uint8list, then do a base64encode on that Uint8List and basically make the widget an anchor element which you can then download.
I've attached some sample code from a project that I was working on that lets the user generate a QR code and download it to the downloads folder on their PC to show what I'm talking about.
Make sure you've imported html at top of dart file:
import 'dart:html' as html;
Then, the code would look something like:
final key = GlobalKey();
final qrTextController = TextEditingController();
//this code "wraps" the qr widget into an image format
RenderRepaintBoundary boundary = key.currentContext!
.findRenderObject() as RenderRepaintBoundary;
//captures qr image
var image = await boundary.toImage();
String qrName = qrTextController.text;
//running on web
if(kIsWeb){
print('registering as a web device');
ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
Uint8List pngBytes = byteData!.buffer.asUint8List();
final _base64 = base64Encode(pngBytes);
final anchor =
html.AnchorElement(href: 'data:application/octet-stream;base64,$_base64')
..download = "image.png"
..target = 'blank';
html.document.body!.append(anchor);
anchor.click();
anchor.remove();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With