How to take a screenshot of the current widget - Flutter

前端 未结 4 712
感动是毒
感动是毒 2020-12-01 06:02

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

4条回答
  •  甜味超标
    2020-12-01 06:23

    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 {
        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);
      });
      

提交回复
热议问题