Save a widget as an image to the gallery using Flutter

Android-only

BatCat
2 min readFeb 4, 2021

I spent a little more time on this feature than I thought would be necessary and I figured that maybe I can save some time for you too.

My setup

Flutter version: 1.26.0

build.gradle:
targetSdkVersion 29
compileSdkVersion 29

Requirements:

  1. Create a screenshot of the widget
  2. Save the screenshot to the user’s device when the user clicks “download”

Permissions:

AndroidManifest.xml

<manifest>
<application>...</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

note: iOS will be added later

You will need to install two plugins: screenshot and gallery_saver and the pubspec.yaml looks like this:

dependencies:
flutter:
sdk: flutter
screenshot: ^0.2.0
gallery_saver: ^2.0.3

After adding these two into YAML file, run flutter pub get in the terminal.

  1. head over to the widget you want to capture and import the two plugins
import 'package:screenshot/screenshot.dart';
import 'package:gallery_saver/gallery_saver.dart';

2. create an instance of the ScreenshotController

ScreenshotController screenshotController = ScreenshotController();

3. find the widget you want to convert to an image and wrap it with Screenshot

Screenshot(
controller: screenshotController,
child: WidgetToConvert(...)

4. create the screenshot

In my use case, the user needs to click on a “Download” icon to create the screenshot and save it to their device

IconButton(
onPressed: () {
screenshotController.capture(pixelRatio: 1.5).then((image) {
GallerySaver.saveImage(
image.path,
albumName: 'myNewAlbum',
).then((success) { print('success')});
}).catchError((err) {
print(err);
});
},
icon: Icon(
Icons.download_rounded,
size: 18,
),
)

The capture method will create the image file and this is what you need to pass to the saveImage method which will return a boolean (success/fail).
Tune pixelRatio to avoid pixelated image.

You can leave the albumName out.

AAAnd you’re done.

Now if you’ll excuse me I have important matters to attend to.

--

--

BatCat
BatCat

Written by BatCat

My mission is to share some of the solutions I find during my journey as a data engineer. I mostly write about PostgreSQL and Python.

No responses yet