Want to save a part of your Flutter app screen as an image? Here's a simple way to do it in just a few steps.
Step 1: Wrap Your Widget
First, put the widget you want to turn into an image inside a RepaintBoundary
widget.
Make sure to give this RepaintBoundary
a GlobalKey
.
final GlobalKey _repaintBoundaryKey = GlobalKey();
// ... inside your build method or wherever your widget is ...
RepaintBoundary(
key: _repaintBoundaryKey,
child: YourWidgetHere(), // <-- This is the widget you want to export
)
Why Use RepaintBoundary?
The GlobalKey
linked to the RepaintBoundary
helps you find the specific part of the screen you want to capture. It lets you get the render object for that widget, which is needed to create the image.
Step 2: Export and Save
Next, you need a function to actually create the image from the widget and save it.
You can use the image_gallery_saver
package for easy saving to the phone's gallery.
Here's how you might do it:
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'dart:ui'; // Import for Image type
import 'dart:typed_data'; // Import for Uint8List
import 'package:flutter/rendering.dart'; // Import for RenderRepaintBoundary
Future<void> exportImage() async {
try {
RenderRepaintBoundary boundary = _repaintBoundaryKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
ui.Image image = await boundary.toImage(pixelRatio: 3.0); // You can adjust pixelRatio
ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List? pngBytes = byteData?.buffer.asUint8List();
if (pngBytes != null) {
final result = await ImageGallerySaver.saveImage(
pngBytes,
quality: 100, // Image quality
name: "my_widget_image_${DateTime.now().millisecondsSinceEpoch}.png", // File name
);
// Optional: Handle the result (e.g., show a success message)
print(result); // Check result status
}
} catch (e) {
// Handle any errors during the process
print("Error exporting image: $e");
}
}
Saving to the Gallery
The code above uses the image_gallery_saver
package. After getting the image data as bytes, this package makes it simple to save that data directly into the user's photo album on their device.
This process lets you quickly capture the visual output of any widget in your app!