How To Easily Take Screenshot In Flutter [Step By Step Guide]

screenshot in flutter

In this tutorial, we’ll learn how to properly take screenshot in Flutter. We’d highly recommend you to follow each step for better and proper understanding. We’ll also display the captured screenshot to prove that it has been taken successfully.

Introduction: Screenshot In Flutter App

In our phone or pc devices, we find the feature called screenshot. This is actually used to capture the current display and show/store it as an image.

In Flutter, we can also implement this feature with ease. We can specify the limit of screenshot like screenshot of whole screen or some specific widget. Let’s now understand how to take screenshot in Flutter step by step using a proper practical Flutter code example.

Implementing Screenshot Feature In Flutter (Step By Step)

Below steps will specify each and every detail we’ll be needing to capture screenshot in Flutter.

Step 1: Global Key

First we’ll need to create a global key. See below code:

static GlobalKey screenshotKey = GlobalKey();
Now we’ve to wrap the widget we want to take screenshot of with repaint boundary and assign our global key to its key constructor. See below:
 RepaintBoundary(
         key: screenshotKey,
         child: Scaffold( appBar: AppBar() )

In our case, we’ve wrapped the Flutter scaffold widget with repaint boundary.

Step 2: Find Render Object

We’ll find the context of our specific widget(in our case, its scaffold) using the key. Then by using this context, we’ll find the render object. We’re using a Flutter material button and we’re specifying that code in its onPressed function. The complete code will be provided in the end. For now, let’s just see the main coding part. See below code:

import 'package:flutter/rendering.dart';   // used for render repaint boundary
RenderRepaintBoundary boundary = screenshotKey.currentContext!.findRenderObject() as RenderRepaintBoundary;

We also have to type cast it from render object to render repaint boundary as shown in the above code.

Using the above code, we’ll able to capture the boundary of that specific widget(wrapped with repaint boundary) and now we’ve to convert it to an image.

Step 3: Convert Object To Image

Now we’ve to use the same boundary to convert the repaint object to an image. Its toImage() method is used for that purpose. The method toImage() has a parameter of name pixel ratio that is used to clear/sharp the image. It takes a double(decimal) value. See below:

ui.Image image = await boundary.toImage(pixelRatio: 3.0);  // by default pixel ratio is 1.0

We’ve used an image variable to hold/store the returned image. We also have referenced the image from ui library as shown in the above code. See below:

import 'dart:ui' as ui;
We can import it like this.

Step 4: Convert Image To Bytes

Now we’ve to convert the image to bytes. We’ll be using the toByteData() method of our image to convert it from image to bytes. It also has a format parameter in which we’ll specify our image byte format to PNG.  See below code:

import 'package:flutter/services.dart';      // used for byte data
ByteData? byte = await image.toByteData(format: ui.ImageByteFormat.png);

Step 5: Convert Bytes To Memory Format

Let’s convert these bytes to memory format. See below:

import 'dart:typed_data';  // used for Uint8List
Uint8List? imageData;
imageData = byte!.buffer.asUint8List();

Step 6: Display The Captured Screenshot

We’ll use a Flutter container widget and inside it, we’ll specify that if the image data is null then do nothing or else show the captures image. See below:

Container(decoration: BoxDecoration(
          image: imageData==null?null: DecorationImage(image: MemoryImage(imageData!))
              ))

Step 7: Test Screenshot In Flutter

Let’s now try to take screenshot and display it. See below:

screenshot in flutter

screenshot in flutter app

So this is how we can properly take screenshot it Flutter and display it. You can store the captured image data as well. Hope you like this article.

Feel free to share it and ask if you still have any queries regarding the implementation of how to take screenshot in Flutter. We’d be very glad to solve all your queries.

Click here if you want a video version of this tutorial.

The complete source code of the above implementation is given in the below section.

Screenshot In Flutter Complete Source Code

import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'dart:ui' as ui;
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(debugShowCheckedModeBanner: false, home: HomePage());
  }
}
class HomePage extends StatefulWidget {
  const HomePage({super.key});
  @override
  State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {

  static GlobalKey screenshotKey = GlobalKey();
  Uint8List? imageData;

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
        key: screenshotKey,
        child: Scaffold(
          appBar: AppBar(),
          body: Center(
              child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                height: 200,
                width: 200,
                margin: EdgeInsets.only(bottom: 40),
                decoration: BoxDecoration(
                    color: Colors.grey.shade100,
                    image: imageData == null
                        ? null
                        : DecorationImage(image: MemoryImage(imageData!))),
              ),

              MaterialButton(
                  onPressed: () async {
                    RenderRepaintBoundary boundary =
                        screenshotKey.currentContext!.findRenderObject()
                            as RenderRepaintBoundary;
                    ui.Image image = await boundary.toImage(pixelRatio: 3.0);
                    ByteData? byte =
                        await image.toByteData(format: ui.ImageByteFormat.png);
                    setState(() {
                      imageData = byte!.buffer.asUint8List();
                    });
                  },
                  color: Colors.blue,
                  textColor: Colors.white,
                  child: Text('Take Screenshot'))

            ],
          )),
        ));
  }
}

Conclusion

In conclusion, now you’ve a proper practical understanding of how to use take screenshot in Flutter. We’ll be more than happy to receive your feedback on this post.

We’d also be very glad to see you visit our other tutorials on Flutter app development. Thank you for reading this article.

Leave a Comment

Your email address will not be published. Required fields are marked *