# screenshot 3.0.0

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




## Installing
```
export PUB_HOSTED_URL=https://pub.mirror.p-hatan.com
flutter pub add 'screenshot:3.0.0'
```
Published: 2024-05-14T11:36:00.674625Z
Expected archive SHA-256: 63817697a7835e6ce82add4228e15d233b74d42975c143ad8cfe07009fab866b

Available in cache; verification: upstream_checksum
## Direct dependencies
- flutter: map[sdk:flutter]

## Package README (untrusted upstream documentation)
 <img src="https://github.com/SachinGanesh/screenshot/raw/master/assets/sc.png" alt="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](https://docs.flutter.io/flutter/rendering/RenderRepaintBoundary-class.html)

[Source](https://stackoverflow.com/a/51118088)

| | | 
| :---: | :---: |
|<img src="https://github.com/SachinGanesh/screenshot/raw/master/assets/screenshot.gif" alt="screenshot"/>|<p>&nbsp; Capture a `widget`:</p><img src="https://github.com/SachinGanesh/screenshot/raw/master/assets/code1.png" alt="screenshot"/><hr><p>&nbsp;Capture an `invisible widget` (a widget which is not part of the widget tree):</p><img src="https://github.com/SachinGanesh/screenshot/raw/master/assets/code2.png" alt="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`

```dart
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();
  }
  ...
}
```
2) Wrap the widget that you want to capture inside `Screenshot` Widget. Assign the controller to `screenshotController` that you have created earlier

```dart
Screenshot(
    controller: screenshotController,
    child: Text("This text will be captured as image"),
),
```

3) Take the screenshot by calling `capture` method. This will return a `Uint8List`

```dart
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

```dart
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.



```dart
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](https://pub.dartlang.org/packages/path_provider)

### Note

>Method `captureAndSave` is not supported for `web`. 


```dart
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 

```dart
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.


```dart
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](https://api.flutter.dev/flutter/flutter_driver/FlutterDriver/screenshot.html). 

```
...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. 

```dart
screenshotController.capture(delay: Duration(milliseconds: 10))
```
---
## Known Issues
- **`Platform Views are not supported. (Example: Google Maps, Camera etc)`[issue](https://github.com/flutter/flutter/issues/83856)**
---
## 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
* 20 Millisecond delay has been added. See issue https://github.com/flutter/flutter/issues/22308
* Example app can now save images directly to Gallery (using https://github.com/hui-z/image_gallery_saver)

## [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.







 
