How to take a screenshot of the current widget - Flutter

29,067

Solution 1

I tried and found the solution,

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static GlobalKey previewContainer = new GlobalKey();
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {

    return RepaintBoundary(
        key: previewContainer,
      child: new Scaffold(
      appBar: new AppBar(

        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(

          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              'You have pushed the button this many times:',
            ),
            new Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
            new RaisedButton(
                onPressed: takeScreenShot,
              child: const Text('Take a Screenshot'),
            ),
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    )
    );
  }
  takeScreenShot() async{
    RenderRepaintBoundary boundary = previewContainer.currentContext.findRenderObject();
    ui.Image image = await boundary.toImage();
    final directory = (await getApplicationDocumentsDirectory()).path;
    ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData.buffer.asUint8List();
    print(pngBytes);
    File imgFile =new File('$directory/screenshot.png');
    imgFile.writeAsBytes(pngBytes);
  }
}

Finally check your application directory You will find screenshot.png !!

And finally got this output

Solution 2

let's say you want to take a screenshot of the FlutterLogo widget . wrap it in a RepaintBoundary with will creates a separate display list for its child . and provide with a key

var scr= new GlobalKey();
RepaintBoundary(
         key: scr,
         child: new FlutterLogo(size: 50.0,))

and then you can get the pngBytes by converting the boundary to an image

takescrshot() async {
  RenderRepaintBoundary boundary = scr.currentContext.findRenderObject();
  var image = await boundary.toImage();
  var byteData = await image.toByteData(format: ImageByteFormat.png);
  var pngBytes = byteData.buffer.asUint8List();
  print(pngBytes);
  }

Solution 3

You can use screenshot plugin to take a widget screenshot.

A screenshot is a simple plugin to capture widgets as Images. This plugin wraps your widgets inside RenderRepaintBoundary

Use this package as a library

  1. Add this to your package's pubspec.yaml file:

    dependencies:
      screenshot: ^0.2.0
    
  2. Now in your Dart code, Import it:

    import 'package:screenshot/screenshot.dart';
    

This handy plugin can be used to capture any Widget including full-screen screenshots & individual widgets like Text().

  1. Create Instance of Screenshot Controller

    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
      File _imageFile;
    
      //Create an instance of ScreenshotController
      ScreenshotController screenshotController = ScreenshotController(); 
    
      @override
      void initState() {
        // TODO: implement initState
        super.initState();
      }
    ...
    }
    
  2. Wrap the widget that you want to capture inside Screenshot Widget. Assign the controller to screenshotController that you have created earlier

    Screenshot(
      controller: screenshotController,
      child: Text("This text will be captured as image"),
    ),
    
  3. Take the screenshot by calling the capture method. This will return a File

    screenshotController.capture().then((File image) {
     //Capture Done
     setState(() {
         _imageFile = image;
     });
    }).catchError((onError) {
     print(onError);
    });
    

Solution 4

here's the solution for flutter 2.0+ method for screenshot and share it on social media

 import 'package:flutter/rendering.dart';
        import 'package:flutter/services.dart';
        import 'dart:ui' as ui;
        import 'package:path_provider/path_provider.dart';
        import 'package:share/share.dart';
        
        GlobalKey previewContainer = new GlobalKey();
    
     @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            // Here we take the value from the MyHomePage object that was created by
            // the App.build method, and use it to set our appbar title.
            title: Text(widget.title),
          ),
          body: RepaintBoundary(
            key: previewContainer,
            child: Center(
              // Center is a layout widget. It takes a single child and positions it
              // in the middle of the parent.
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    'Take Screen Shot',
                  ),
                ],
              ),
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _captureSocialPng,
            tooltip: 'Increment',
            child: Icon(Icons.camera),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        );
      }
    
        
          Future<void> _captureSocialPng() {
            List<String> imagePaths = [];
            final RenderBox box = context.findRenderObject() as RenderBox;
            return new Future.delayed(const Duration(milliseconds: 20), () async {
              RenderRepaintBoundary? boundary = previewContainer.currentContext!
                  .findRenderObject() as RenderRepaintBoundary?;
              ui.Image image = await boundary!.toImage();
              final directory = (await getApplicationDocumentsDirectory()).path;
              ByteData? byteData =
                  await image.toByteData(format: ui.ImageByteFormat.png);
              Uint8List pngBytes = byteData!.buffer.asUint8List();
              File imgFile = new File('$directory/screenshot.png');
              imagePaths.add(imgFile.path);
              imgFile.writeAsBytes(pngBytes).then((value) async {
                await Share.shareFiles(imagePaths,
                    subject: 'Share',
                    text: 'Check this Out!',
                    sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
              }).catchError((onError) {
                print(onError);
              });
            });
          }

Solution 5

Run

flutter screenshot

It will take the screenshot from your connected device and save that to your folder in which you are doing development it will save flutter_01.jpg like that in your folder

Share:
29,067
Prabhu
Author by

Prabhu

Updated on October 19, 2021

Comments

  • Prabhu
    Prabhu over 2 years

    I need to take a screenshot of the current screen or widget and I need to write it into a file.