screenshot

3.0.0

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

Download archive

Readme

A simple package to capture widgets as Images. Now you can also capture the widgets that are not rendered on the screen!

This package wraps your widgets inside RenderRepaintBoundary

Source

  Capture a widget: Capture an invisible widget (a widget which is not part of the widget tree):

Getting Started

This handy package 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;
  Uint8List _imageFile;

  //Create an instance of ScreenshotController
  ScreenshotController screenshotController = ScreenshotController(); 

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }
  ...
}
  1. 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"),
),
  1. Take the screenshot by calling capture method. This will return a Uint8List
screenshotController.capture().then((Uint8List image) {
    //Capture Done
    setState(() {
        _imageFile = image;
    });
}).catchError((onError) {
    print(onError);
});

Capturing Widgets that are not in the widget tree

You can capture invisible widgets by calling captureFromWidget and passing a widget tree to the function

screenshotController
      .captureFromWidget(Container(
          padding: const EdgeInsets.all(30.0),
          decoration: BoxDecoration(
            border:
                Border.all(color: Colors.blueAccent, width: 5.0),
            color: Colors.redAccent,
          ),
          child: Text("This is an invisible widget")))
      .then((capturedImage) {
    // Handle captured image
  });


Capturing a List Widget

You can capture a long Invisible widgets by using captureFromLongWidget function.

var randomItemCount = Random().nextInt(100);

///
/// Step 1: Create Long widget using Column.
///

var myLongWidget = Builder(builder: (context) {
  return Container(
      padding: const EdgeInsets.all(30.0),
      decoration: BoxDecoration(
        border:
            Border.all(color: Colors.blueAccent, width: 5.0),
        color: Colors.redAccent,
      ),
      ///
      /// Note: Do not use Scrolling widget, instead place your children in Column. 
      ///  
      /// Do not use widgets like 'Expanded','Flexible',or 'Spacer'
      ///
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          for (int i = 0; i < randomItemCount; i++)
            Text("Tile Index $i"),
        ],
      ));
});

///
/// Step 2: 
///    Use `captureFromLongWidget` function for taking screenshot.
///
screenshotController
      .captureFromLongWidget(
          InheritedTheme.captureAll(
            context, 
            Material(
              child: myLongWidget,
            ),
          ),
          delay: Duration(milliseconds: 100),
          context: context,


          ///
          /// Additionally you can define constraint for your image.
          ///
          /// constraints: BoxConstraints(
          ///   maxHeight: 1000,
          ///   maxWidth: 1000,
          /// )
      )
      .then((capturedImage) {
    // Handle captured image
  });


Saving images to Specific Location

For this you can use captureAndSave method by passing directory location. By default, the captured image will be saved to Application Directory. Custom paths can be set using path parameter. Refer path_provider

Note

Method captureAndSave is not supported for web.

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

Saving images to Gallery

If you want to save captured image to Gallery, Please use https://github.com/hui-z/image_gallery_saver Example app uses the same to save screenshots to gallery.


Sharing Captured Images

await _screenshotController.capture(delay: const Duration(milliseconds: 10)).then((Uint8List image) async {
      if (image != null) {
        final directory = await getApplicationDocumentsDirectory();
        final imagePath = await File('${directory.path}/image.png').create();
        await imagePath.writeAsBytes(image);

        /// Share Plugin
        await Share.shareFiles([imagePath.path]);
      }
    });

Note:

Captured image may look pixelated. You can overcome this issue by setting value for pixelRatio

The pixelRatio describes the scale between the logical pixels and the size of the output image. It is independent of the window.devicePixelRatio for the device, so specifying 1.0 (the default) will give you a 1:1 mapping between logical pixels and the output pixels in the image.

double pixelRatio = MediaQuery.of(context).devicePixelRatio;

screenshotController.capture(
    pixelRatio: pixelRatio //1.5
)

Sometimes rastergraphics like images may not be captured by the plugin with default configurations. The issue is discussed here.

...screenshot is taken before the GPU thread is done rasterizing the frame 
so the screenshot of the previous frame is taken, which is wrong.

The solution is to add a small delay before capturing.

screenshotController.capture(delay: Duration(milliseconds: 10))

Known Issues

  • Platform Views are not supported. (Example: Google Maps, Camera etc)issue

Changelog

[3.0.0] - 14/05/2024

  • Make API Changes compatible with Flutter 3.22.0
  • BREAKING CHANGE: Add flutter version constraint to be >=3.22.0. This will break for lower versions of Flutter.

[2.5.0] - 14/05/2024

  • Revert Changes from 2.4.0 release.
  • BREAKING CHANGE: Add flutter version constraint to be <3.22.0

[2.4.0] - 14/05/2024

  • Update ViewConfiguration parameters.
  • BREAKING CHANGE: This will throw Compile time error for versions <=3.19.

[2.3.0] - 15/03/2024

  • Revert ViewConfiguration ViewConfiguration parameters in widgetToUiImage to match API with size parameter .
  • BREAKING CHANGE: This will throw Compile time error for versions >=3.18 and <=3.19 and for some Pre release versions.

[2.2.0] - 15/03/2024

  • Update ViewConfiguration ViewConfiguration parameters in widgetToUiImage to match API with constraint parameter.
  • BREAKING CHANGE: This will throw Compile time error for versions <=3.18 and >=3.19.

[2.1.0] - 13/05/2023

  • New Functions: captureFromLongWidget and longWidgetToUiImage. Calculates widgets size and captures whole widget at once.
  • BREAKING CHANGE: add minimum flutter version constraint. so if your project is below flutter 3.10, Please consider using version 1.3.0

[2.0.0] - 13/05/2023

  • BREAKING CHANGE: supports flutter version >=3.10 only.
  • Migrate to FlutterView from ui.window @Mayb3Nots

[1.3.0] - 27/12/2022

  • Fix disposing widgets after capturing in widgetToUiImage function @Lan-tb

[1.2.3] - 15/07/2021

  • Support Inheriting Theme for Invisible Widget

[1.2.2] - 14/07/2021

  • Add pixelRatio to captureFromWidget @hashirshoaeb
  • Fix assertion issue

[1.2.1] - 13/06/2021

  • Removal of compilation warning @yanivshaked

[1.2.0] - 13/06/2021

  • Add support for invisible widget capture

[1.0.0-nullsafety.0] - 10/02/2021

  • Add nullsafety

[0.3.0] - 10/02/2021

  • breaking change capture method returns Uint8List instead of File.
  • support for web and windows
  • Add captureAndSave method.

[0.2.0] - 10/06/2020

  • Add captureAsUiImage method

[0.1.1] - 11/05/2019

[0.1.0] - 09/05/2019

  • changed path_provider version to ^1.1.0

[0.0.2] - 16/02/2019

  • added support for older versions of path provider

[0.0.1] - 12/02/2019

  • initial release.

Installing

export PUB_HOSTED_URL=https://pub.mirror.p-hatan.com
flutter pub add screenshot
pubspec.yaml
name: screenshot
description: Flutter Screenshot Package (Runtime). Capture any Widget as an image.
version: 3.0.0
homepage: https://github.com/SachinGanesh/screenshot

environment:
  sdk: '>=2.12.0 <4.0.0'
  flutter: '>=3.22.0'

# analyzer:
#   enable-experiment:
#     - non-nullable
dependencies:
  flutter:
    sdk: flutter

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec
# The following section is specific to Flutter.
flutter: null

# To add assets to your package, add an assets section, like this:
# assets:
#  - images/a_dot_burr.jpeg
#  - images/a_dot_ham.jpeg
#
# For details regarding assets in packages, see
# https://flutter.io/assets-and-images/#from-packages
#
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.io/assets-and-images/#resolution-aware.
# To add custom fonts to your package, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
#   - family: Schyler
#     fonts:
#       - asset: fonts/Schyler-Regular.ttf
#       - asset: fonts/Schyler-Italic.ttf
#         style: italic
#   - family: Trajan Pro
#     fonts:
#       - asset: fonts/TrajanPro.ttf
#       - asset: fonts/TrajanPro_Bold.ttf
#         weight: 700
#
# For details regarding fonts in packages, see
# https://flutter.io/custom-fonts/#from-packages

Version history

VersionPublishedArchiveSHA-256
0.0.1On demandDownloadcacace36…9d3b69
0.0.2On demandDownload22dd5ad5…e9cfe8
0.1.0On demandDownload2e66b323…b3da89
0.1.1On demandDownload31ca903b…179a1e
0.2.0On demandDownload7b187dd1…089790
0.3.0On demandDownload3b96c5dd…abdd63
1.0.0-nullsafety.1On demandDownload633ee2ed…e9a72a
1.1.0On demandDownloadc49ff66b…827780
1.2.0On demandDownload44afa0a1…5e9c88
1.2.1On demandDownload31a0f50f…0b15f8
1.2.2On demandDownloadca52dca8…6c1f02
1.2.3On demandDownload50d6ee74…d733a4
1.3.0On demandDownload30bb9fad…b728e2
2.0.0On demandDownload65d4050f…d8efb2
2.1.0On demandDownload455284ff…c7b81c
2.2.0On demandDownload5f263a25…e780d0
2.3.0On demandDownload54881350…2ebf95
2.4.0On demandDownload50414491…f84cbd
2.5.0On demandDownloadd448f431…5e2aee
3.0.0Cached · Upstream SHA-256 matchedDownload63817697…ab866b

Dependencies

flutter { "sdk": "flutter" }