How to take screenshot in Flutter

How to implement screenshots on your Flutter app programatically.

· 2 min read
How to take screenshot in Flutter

Hello everyone, In this article, I am going to discuss how you can take screenshots using Flutter.

To implement this we are going to user screenshot plugin. This plugin allows capturing widgets as images. It even allows you to captures the widgets that are not rendered on the screen.

Plugin Installation

To install the plugin simply add the dependency in your pubspec.yaml file. And run pub get command to fetch install the plugin.

screenshot: ^1.2.3

It will look something like this.

pubspec.yaml

Now the plugin has been installed. Let's move on to implementation.

Implementation

To show implementation I will begin with the basic Flutter app.

  1. Import the plugin on your screen
import 'package:screenshot/screenshot.dart';

2. Then we have to make an instance of ScreenshotController on your screen class.

ScreenshotController screenshotController = ScreenshotController();

Like in my code it looks something like this.

3. To capture any widget using this plugin, we have to wrap that widget inside the Screenshot widget. And have to attach the controller declared in the above code.

Screenshot(
        controller: screenshotController,
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: const <Widget>[
              Text(
                'This screen is being captured',
              ),
            ],
          ),
        ),
      ),
main.dart

4. Now to capture the wrapped widget call this method.

screenshotController.capture().then((Uint8List? image) {

}).catchError((onError) {
    print(onError);
});

This method returns an image of the type Uint8List. We can save this image on our device once it finished capturing the screen.

5. You can save the captured image in the gallery using this code.

if (image != null) {
        final directory = await getApplicationDocumentsDirectory();
        final imagePath = await File('${directory.path}/image.png').create();
        await imagePath.writeAsBytes(image);
      }

6. To save the image in custom directory use this code.

final directory = (await getApplicationDocumentsDirectory ()).path; //from path_provide package
String fileName = DateTime.now().microsecondsSinceEpoch;
path = '$directory';

screenshotController.captureAndSave(
    path //set path where screenshot will be saved
    fileName:fileName 
);

7. You can also share the image using the share plugin.

So this is how you can implement screen capturing on your Flutter app. To discover more about the plugin, please go through the plugin page.

screenshot | Flutter Package
Flutter Screenshot Package (Runtime). Capture any Widget as an image.

I hope you had found this article helpful. If you have any problems, you can ask me in the comment section.