Code Monkey home page Code Monkey logo

screenshot's Introduction

screenshot

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

screenshot

  Capture a widget:

screenshot

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

screenshot

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

screenshot's People

Contributors

dbilgin avatar gallinaettore avatar hashirshoaeb avatar mayb3nots avatar rignaneseleo avatar ritheshsalyan avatar sachinganesh avatar yanivshaked avatar yonatan-yna avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

screenshot's Issues

Animations capture

Hi

I am working with animations in my app

there are any way to convert the animations in video o gif ?

`capture()` method does not work on Windows

capture() method does not work on Windows because the paths in windows use \ while your package is using / which works for other platforms. I would suggest adding a check to see if the platform is windows or not and add the path separator accordingly

Image in gallery picture is black

      this._screenshotOwner
                  .capture(delay: Duration(milliseconds: 10), pixelRatio: 3)
                  .then((File captureImage) async {
                Map<PermissionGroup, PermissionStatus> permissionResult = await PermissionHandler().requestPermissions([PermissionGroup.storage]);
                if (permissionResult[PermissionGroup.storage] != PermissionStatus.granted) throw "Permission Denied";
                final result = await ImageGallerySaver.saveImage(captureImage.readAsBytesSync());
                print(result);
              });

Screenshot is blurred on iPad Pro 9.7

I'm trying to capture a screenshot of a drawing. On the phone is works great.
On an iPad pro iOS 14.4 (didn't try others) it is very blurred. Trying different pixel ratio parameters doesn't seem to help.

Using the latest version of Screenshot.

Not an issue more of a suggestion.

Is there a way to implement watermarks for the screenshots you take? I have been trying to figure out how can that be possible. I tried using the visibility widget but to no avail sadly.

Capture Widget without context

I have to add an image to my MapBox map so I want to build a Widget, capture it as an image, and then send it into the map. The Widget is not going to be rendered on-screen at all in the context. Here's my code for creating the image and passing it to the MapBoxController:

Future<void> _addImageFromPOI(MapboxMapController controller, POI poi) async {
    // Create an image from the POI icon information
    // Needs to build a widget and then draw an image of it for use on the map
    // Uint8List _imageFile;
    ScreenshotController screenshotController = ScreenshotController();
    POIWidget widget = POIWidget(poi: poi);
    Screenshot(
      controller: screenshotController,
      child: widget,
    );
    await screenshotController.capture().then((Uint8List image) {
      controller.addImage(poi.docId, image);
      controller.addSymbol(
        SymbolOptions(
          geometry: LatLng(poi.latitude, poi.longitude),
          iconImage: poi.docId,
        ),
      );
    }).catchError((onError) {
      print(onError);
    });
  }

... and I am getting an error:

The method 'findRenderObject' was called on null. - I suspect that this is because the Widget is not being rendered on the context. Is this correct?

in flutter web not working

screenshotController.capture().then((Uint8List image) {
//Capture Done
setState(() {
_imageFile = image;
print("the image file is "+_imageFile.toString());
});
}).catchError((onError) {
print(onError);
});

iam using this code its working fine in mobile(android+ios) but not working in web
throwing this error -- "Unsupported operation: toImage is not supported on the Web"

clipBehavior = Clip.none

Is it possible to take the screenshot of this entire widget?

Stack(
  clipBehavior: Clip.none,
  alignment: Alignment.center,
  children: [
    Container(
      color: Colors.red,
      width: 20,
      height: 20,
    ),
    Positioned(
      top: -10,
      child: Container(
        color: Colors.green,
        width: 20,
        height: 20,
      ),
    ),
    Positioned(
      top: -20,
      child: Container(
        color: Colors.bue,
        width: 20,
        height: 20,
      ),
    ),
  ],
)

I'm only getting the first one and the half of the second one; probably because the other ones are being overflown

Is this working on web?

I am trying to use this with flutter web but I think it might be not supported because I get an error:

Assertion failed: org-dartlang-sdk:///flutter_web_sdk/lib/_engine/engine/surface/scene_builder.dart:111:16
matrix4[0] == window.devicePixelRatio &&
           matrix4[5] == window.devicePixelRatio
is not true

save in jpg

Hello, is there a solution to save the screenshot as jpg ?
or maybe a way to convert the png in jpg not using image plugin...

thank you so much for your help !

Request :

Ability to capture screenshots of individual widgets in a list

Allow screenshots with specific dimensions

The plugin works pretty well, but when I export the image it is saved as a full page screenshot with the widget that I am taking screenshot of in center and black area on top and bottom. Is it possible to create dimensions that we can use to take screenshot like providing a specific height and width. Or cropping it to the specified dimensions before saving in gallery.

Widget Google Map not captured

This plugin not captured widget Google Map.

bug_screenshot

flutter doctor -v

[✓] Flutter (Channel beta, 1.24.0-10.2.pre, on Mac OS X 10.15.7 19H2 darwin-x64, locale en-EC)
    • Flutter version 1.24.0-10.2.pre at /Users/yudisetiawan/fvm/versions/beta
    • Framework revision 022b333a08 (4 weeks ago), 2020-11-18 11:35:09 -0800
    • Engine revision 07c1eed46b
    • Dart version 2.12.0 (build 2.12.0-29.10.beta)

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at /Users/yudisetiawan/Library/Android/sdk
    • Platform android-30, build-tools 30.0.2
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 12.0.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.0.1, Build version 12A7300
    • CocoaPods version 1.10.0

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] IntelliJ IDEA Community Edition (version 2020.2.3)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.50.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.16.0

[✓] Connected device (3 available)
    • Redmi Note 4 (mobile) • faa168ce9804 • android-arm64  • Android 7.0 (API 24)
    • Web Server (web)      • web-server   • web-javascript • Flutter Tools
    • Chrome (web)          • chrome       • web-javascript • Google Chrome 87.0.4280.88

• No issues found!

debugNeedsPaint is not true

Hello, just implemented this package, when I call:

final captureImage = await screenshotController.captureAsUiImage(pixelRatio: 2);
final data = await captureImage.toByteData(format: ui.ImageByteFormat.png);
return CaptureResult(data?.buffer?.asUint8List(), captureImage.width, captureImage.height);

I got this error:

E/flutter (25668): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: 'package:flutter/src/rendering/proxy_box.dart': Failed assertion: line 2958 pos 12: '!debugNeedsPaint': is not true.
E/flutter (25668): #0      ScreenshotController.captureAsUiImage.<anonymous closure>
package:screenshot/screenshot.dart:78
E/flutter (25668): #1      new Future.delayed.<anonymous closure> (dart:async/future.dart:326:39)
E/flutter (25668): #2      _rootRun (dart:async/zone.dart:1182:47)
E/flutter (25668): #3      _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (25668): #4      _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter (25668): #5      _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
E/flutter (25668): #6      _rootRun (dart:async/zone.dart:1190:13)
E/flutter (25668): #7      _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (25668): #8      _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1021:23)
E/flutter (25668): #9      Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter (25668): #10     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:397:19)
E/flutter (25668): #11     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:428:5)
E/flutter (25668): #12     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
E/flutter (25668):

Please help. Thank you.

Flutter GoogleMaps RepaintsBoundary. toImage() Crashes on Web

Steps to reproduce:

  1. On Flutter Web, Wrap Flutter Google Maps in a RepaintBoundary

Like so:

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      key: ScreenShotable.previewContainer,
      child: widget.child,
    );
  }

Usage:

final img = await screenshotController.captureAsUiImage(
        Container(
          height: 100,
          width: 100,
          color: Colors.brown,
          child: GoogleMap(
            initialCameraPosition: CameraPosition(
              target: FlitLatLng(-20.1020344, 57.5621812999999).toLatLng(),
              zoom: 13.0,
            ),
            rotateGesturesEnabled: false,
            tiltGesturesEnabled: false,
            // markers: Set<Marker>.of(controller.markers.values),
          ),
        ),
        delay: Duration(seconds: 6));

ScreenshotControllers.captureAsUiImage

RenderRepaintBoundary boundary =
    this.view!.context.findRenderObject() as RenderRepaintBoundary;
ui.Image image = await boundary.toImage(pixelRatio: pxRatio); // crash here

Actual:

Error: Unexpected null value.
    at Object.throw_ [as throw] (http://localhost:49196/dart_sdk.js:5037:11)
    at Object.nullCheck (http://localhost:49196/dart_sdk.js:5362:30)
    at _engine.PlatformViewLayer.new.preroll (http://localhost:49196/dart_sdk.js:135222:12)
    at _engine.OffsetEngineLayer.new.prerollChildren (http://localhost:49196/dart_sdk.js:134614:15)
    at _engine.OffsetEngineLayer.new.preroll (http://localhost:49196/dart_sdk.js:134881:35)
    at _engine.OffsetEngineLayer.new.prerollChildren (http://localhost:49196/dart_sdk.js:134614:15)
    at _engine.OffsetEngineLayer.new.preroll (http://localhost:49196/dart_sdk.js:134881:35)
    at _engine.TransformEngineLayer.new.prerollChildren (http://localhost:49196/dart_sdk.js:134614:15)
    at _engine.TransformEngineLayer.new.preroll (http://localhost:49196/dart_sdk.js:134881:35)
    at _engine.RootLayer.new.prerollChildren (http://localhost:49196/dart_sdk.js:134614:15)
    at _engine.RootLayer.new.preroll (http://localhost:49196/dart_sdk.js:134609:31)
    at _engine.LayerTree.new.flatten (http://localhost:49196/dart_sdk.js:135508:22)
    at _engine.LayerScene.new.toImage (http://localhost:49196/dart_sdk.js:135263:36)
    at layer$.OffsetLayer.new.toImage (http://localhost:49196/packages/flutter/src/rendering/layer.dart.js:1327:30)
    at toImage.next (<anonymous>)
    at runBody (http://localhost:49196/dart_sdk.js:37393:34)
    at Object._async [as async] (http://localhost:49196/dart_sdk.js:37424:7)
    at layer$.OffsetLayer.new.toImage (http://localhost:49196/packages/flutter/src/rendering/layer.dart.js:1318:20)
    at proxy_box.RenderRepaintBoundary.new.toImage (http://localhost:49196/packages/flutter/src/rendering/proxy_box.dart.js:3096:26)
    at captureFromWidget (http://localhost:49196/packages/screenshot/screenshot.dart.js:242:44)
    at captureFromWidget.next (<anonymous>)
    at http://localhost:49196/dart_sdk.js:37374:33
    at _RootZone.runUnary (http://localhost:49196/dart_sdk.js:37245:59)
    at _FutureListener.thenAwait.handleValue (http://localhost:49196/dart_sdk.js:32501:29)
    at handleValueCallback (http://localhost:49196/dart_sdk.js:33028:49)
    at Function._propagateToListeners (http://localhost:49196/dart_sdk.js:33066:17)
    at _Future.new.[_complete] (http://localhost:49196/dart_sdk.js:32906:25)
    at http://localhost:49196/dart_sdk.js:32085:30
    at internalCallback (http://localhost:49196/dart_sdk.js:24224:11)

Expected:

No crash. Even better if we get the screenshot of the map.
On Mobile, we get blank screen.

Further debugging:

I tried with my own code above and even with the https://pub.dev/packages/screenshot package. Same result

If you have any clue on what the error above means, I would appreciate, even a small comment. It will help me find a workaround

Compilation warning

Note the following compilation warning; delay is not nullable so the ?? operation is redundant.

/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/screenshot-1.1.0/lib/screenshot.dart:45:31: Warning: Operand of null-aware operation '??' has type 'Duration' which excludes null.
 - 'Duration' is from 'dart:core'.
    return new Future.delayed(delay ?? Duration(milliseconds: 20), () async {

Screenshot not coming fully

I'm having multiple tables which are introduced inside a SingleChildScrollView. I'm using the Screensot as the parent widget in the body of the Scaffold, but when i caputre the screenshot I'm just getting the image only which is visible to the user but not all the tables when scrolled down/up.


ScreenshotController screenshotController = ScreenshotController();

body: Screenshot(
        controller: screenshotController,
        child: TabBarView(
          children: [
            SingleChildScrollView(
              child: Padding(
                padding: EdgeInsets.only(bottom: 50.h.toDouble()),
                child: Column(children: v0),
              ),
            ),
            SingleChildScrollView(child: Column(children: v1)),
            SingleChildScrollView(child: Column(children: v2)),
            SingleChildScrollView(child: Column(children: v3)),
          ],
          controller: _tabController,
        ),
      ),

And the onPress function while capturing the screenshot

CaptureScreenshot() async {
    final uint8List = await screenshotController.capture();
    String tempPath = (await getTemporaryDirectory()).path;
    File file = File('$tempPath/image.png');
    await file.writeAsBytes(uint8List!);
    await Share.shareFiles([file.path]);
  }

And as i've went through other answers in issues found that the ScreenShot widget should be placed inside a SingleChildScrollView but if i use the SingleChildScrollView as the parent widget for the ScreenShot widget I'm getting an error as

RenderBox was not laid out: RenderRepaintBoundary#4b20b relayoutBoundary=up1 NEEDS-PAINT
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'


Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.

Issue with google maps

Hello,
I tried using this plugin with a widget with google maps in it. It captures the screen but without the maps part. It appears blank.
Appreciate if you can help.

Thanks

Directory usage is quite difficult to understand.

Please document somewhere that the App directory cannot be read from another app, this is by design and I understand this fully. When the image is stored in the App directory(as suggested in your write-up) gMail app cannot attach the file. I would suggest to use the Temp directory for this instead of the App directory. Also with a mention about this intricate situation.

Mario

Screenshot animation

It would be useful for UX to have a screenshot animation, when the screenshot is taken - maybe something similar to this.

'logicalSize.aspectRatio == imageSize.aspectRatio': is not true.

Excellent Package you got here! So I tried capturing invisible widget but I get this error which I can't fathom.

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: 'package:screenshot/screenshot.dart': Failed assertion: line 92 pos 12: 'logicalSize.aspectRatio == imageSize.aspectRatio': is not true.
E/flutter ( 6791): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
E/flutter ( 6791): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
E/flutter ( 6791): #2      ScreenshotController.captureFromWidget (package:screenshot/screenshot.dart:92:12)
E/flutter ( 6791): #3      _BeginState.build.<anonymous closure> (package:Phoenix/src/Begin/begin.dart:243:50)
E/flutter ( 6791): #4      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
E/flutter ( 6791): #5      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter ( 6791): #6      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:607:11)
E/flutter ( 6791): #7      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
E/flutter ( 6791): #8      BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:230:7)
E/flutter ( 6791): #9      PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:475:9)
E/flutter ( 6791): #10     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:93:12)
E/flutter ( 6791): #11     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:138:9)
E/flutter ( 6791): #12     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:397:8)
E/flutter ( 6791): #13     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:136:18)
E/flutter ( 6791): #14     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:122:7)
E/flutter ( 6791): #15     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:439:19)
E/flutter ( 6791): #16     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
E/flutter ( 6791): #17     RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:287:11)
E/flutter ( 6791): #18     GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
E/flutter ( 6791): #19     GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
E/flutter ( 6791): #20     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
E/flutter ( 6791): #21     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
E/flutter ( 6791): #22     _rootRunUnary (dart:async/zone.dart:1370:13)
E/flutter ( 6791): #23     _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter ( 6791): #24     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter ( 6791): #25     _invoke1 (dart:ui/hooks.dart:182:10)
E/flutter ( 6791): #26     PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:282:7)
E/flutter ( 6791): #27     _dispatchPointerDataPacket (dart:ui/hooks.dart:96:31)

I used the same code used in the example

  IconButton(
      icon: Icon(Ionicons.barcode_outline),
      color: Colors.white,
      iconSize: deviceWidth / 18,
      onPressed: () {
        ScreenshotController screenshotController = ScreenshotController();
        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
        });
      });

Would you please help me out here?

Edit: Turns out this only happens in debug mode and works fine in release. I don't know whether this is an intended behavior or not. If it is intended, then feel free to close this issue.

Getting "NoSuchMethodError: The method 'toImage' was called on null." Exception

screenshot: ^0.2.0 was working perfectly fine till I updated Flutter to 2.0 and Screenshot Package to screenshot: ^1.0.0-nullsafety.1 I started getting "NoSuchMethodError: The method 'toImage' was called on null." exception.
I'm calling screenshotController.capture() method.
The exception is thrown inside captureAsUiImage() method when it tries to call boundary.toImage(...);

This happens when I try to capture multiple widgets screenshot.
I've multiple CardView inside a Column which is wrapped with Screenshot widget. When I try to all .capture() for each ScreenshotController only the first call to capture works and for the rest it throws NoSuchMethodError
I've also tried increasing the delay, however, no success.

Saving a list of widgets throws findRenderObject was called on null exception.

I have a list of items in
ListView(), not ListView.builder(). And in the ListView each child is wrapped with Screenshot widget.
When the ListView is built I store the Screenshot controller for each widget in a list.
When trying to capture only the first widget gets captured and then I get this exception

/flutter ( 2557): Caught error: NoSuchMethodError: The method 'findRenderObject' was called on null.
I/flutter ( 2557): Receiver: null
I/flutter ( 2557): Tried calling: findRenderObject()
I/flutter ( 2557): #0      ScreenshotController.capture.<anonymous closure>
package:screenshot/screenshot.dart:41
I/flutter ( 2557): #1      new Future.delayed.<anonymous closure> (dart:async/future.dart:326:39)
I/flutter ( 2557): #2      _rootRun (dart:async/zone.dart:1182:47)
I/flutter ( 2557): #3      _CustomZone.run (dart:async/zone.dart:1093:19)
I/flutter ( 2557): #4      _CustomZone.runGuarded (dart:async/zone.dart:997:7)
I/flutter ( 2557): #5      _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
I/flutter ( 2557): #6      _rootRun (dart:async/zone.dart:1190:13)
I/flutter ( 2557): #7      _CustomZone.run (dart:async/zone.dart:1093:19)
I/flutter ( 2557): #8      _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1021:23)
I/flutter ( 2557): #9      Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
I/flutter ( 2557): #10     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:397:19)
I/flutter ( 2557): #11     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:428:5)
I/flutter ( 2557): #12     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)

Broken text styling when using Theme.of(context).textTheme

Text styling in my screenshot goes bananas when I style with Theme.of(context).textTheme.* but the screenshot will look okay if I hardcode text styles. This was reproducible in our iOS and Android emulators with Flutter v2.0.6 and screenshot: ^1.2. Examples below, let us know if there's anything else that'll be useful to provide for debugging!

Hardcoded Text Style Example
What screenshot looks like when we are hardcoding text style (which is correct and matches what widget looks like in app):

Screen Shot 2021-06-28 at 8 24 11 PM

// Widget code that gets captured
return Column(
      children: [
        Text(
          'Title Header Font 24',
          textAlign: TextAlign.center,
          style: TextStyle( // <----- hardcoded to match our Theme.of(context).textTheme.headline6
            fontFamily: 'Rubik',
            fontSize: 24,
            color: Colors.black,
            height: 1,
          ),
        ),
        Text(
          'Tilte Font 40',
          textAlign: TextAlign.center,
          style: TextStyle( // <----- hardcoded to match our Theme.of(context).textTheme.headline1
            fontFamily: 'Rubik',
            fontSize: 40,
            fontWeight: FontWeight.bold,
            color: Colors.black,
            height: 1,
          ),
        ),
      ],
    );

Broken Styling Using Theme Example
When using Theme.of(context).textTheme:
Screen Shot 2021-06-28 at 8 23 46 PM

// Widget code that gets captured
return Column(
      children: [
        Text(
          'Title Header Font 24',
          textAlign: TextAlign.center,
          style: Theme.of(context).textTheme.headline6,
        ),
        Text(
          'Tilte Font 40',
          textAlign: TextAlign.center,
          style: Theme.of(context).textTheme.headline1,
        ),
      ],
    );

In case it's useful, this is how we're capturing:

final ScreenshotController controller = ScreenshotController();
final Uint8List imageBytes = await controller.captureFromWidget(widget);
final String tempPath = (await getTemporaryDirectory()).path;
final File file = File('$tempPath/$filename');
// Render a preview of cached image file in the app + combine with share extensions

font in pubspec.yaml

flutter:
  fonts:
    - family: Rubik
      fonts:
        - asset: assets/fonts/Rubik-Regular.ttf
        - asset: assets/fonts/Rubik-Bold.ttf
          weight: 700

PDFTron view cannot capture in screenshot.

Hi,

We are using PDFTron for viewing PDF in Flutter but when we use the screenshot, it is not showing. The rest of the screen can capture except for the pdftron documentview.

PaintContext does not support embedding

I am trying to take screenshot of web page (WebView) on my app. It is giving below error.

E/flutter (10118): [ERROR:flutter/flow/layers/platform_view_layer.cc(25)] Trying to embed a platform view but the PrerollContext does not support embedding
E/flutter (10118): [ERROR:flutter/flow/layers/platform_view_layer.cc(40)] Trying to embed a platform view but the PaintContext does not support embedding

how to capture entire screen like PrtSc

It is helping me only to capture the flutter application screen/widget even I am using any other application. But I want to track all activities on the machine while flutter application is running in background. for example when flutter app is running in background and chrome is active on screen, it should capture present visible screen of the machine.

Question - Screenshot Extended

Hello, guys!

Would it be possible to take a 'printscreen' of the entire application window? As if it were a printscreen (manual) where an 'extender' button appears?
Because in my application there is information down there and the 'printscreen' cannot remove it from the bottom of the window.

Can someone help me?
Thanks!

license

what's your license please?

Null Safety Support

Is there any version related to null safety support? I couldn't find it. If not, is there any plan to do it?

Convert Uint8List to File

I am using the previous version 0.2.0 of screenshot and it support capture as File. With the new 0.3.0, it is now Uint8List.
How do I convert Uint8List into File ?

Screenshot elements not rendered on screen?

Hello @SachinGanesh thanks for the package. I'm trying to screenshot a part of the widget tree but I need to add some custom widgets to the screenshot, those widgets in the screenshot should not be shown on the screen. Is there a way to achieve this using this package?

when i click add button, throw an error

W/System.err(25434): java.io.FileNotFoundException: /storage/emulated/0/example/1572487834458.png (No such file or directory)
W/System.err(25434): at java.io.FileOutputStream.open0(Native Method)
W/System.err(25434): at java.io.FileOutputStream.open(FileOutputStream.java:308)
W/System.err(25434): at java.io.FileOutputStream.(FileOutputStream.java:238)
W/System.err(25434): at java.io.FileOutputStream.(FileOutputStream.java:180)
W/System.err(25434): at com.example.imagegallerysaver.ImageGallerySaverPlugin.saveImageToGallery(ImageGallerySaverPlugin.kt:61)
W/System.err(25434): at com.example.imagegallerysaver.ImageGallerySaverPlugin.onMethodCall(ImageGallerySaverPlugin.kt:33)
W/System.err(25434): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:222)
W/System.err(25434): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:96)
W/System.err(25434): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:656)
W/System.err(25434): at android.os.MessageQueue.nativePollOnce(Native Method)
W/System.err(25434): at android.os.MessageQueue.next(MessageQueue.java:332)
W/System.err(25434): at android.os.Looper.loop(Looper.java:168)
W/System.err(25434): at android.app.ActivityThread.main(ActivityThread.java:6867)
W/System.err(25434): at java.lang.reflect.Method.invoke(Native Method)
W/System.err(25434): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
W/System.err(25434): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)

platform: android
android version: 9.1
flutter doctor:
[✓] Flutter (Channel stable, v1.9.1+hotfix.5, on Mac OS X 10.14.5 18F132, locale en-CN)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 11.0)
[✓] Android Studio (version 3.4)
[✓] VS Code (version 1.39.1)
[✓] Connected device (1 available)

Is it work in Webview?

I have been trying to screen capture a picture of WebView and the result that I get is an empty picture. Do you have a solution to solve them? I had no error in the command line, it only sent me an empty picture. Thank you in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.