Flutter save widget directly into an image

Viewed 3834

I have a custom widget that I want to save into a png image. The issue I'm facing is that with the current implementation is that I'm required to show the widget on the screen. What I want is to save the widget directly into the image without showing it.

As a workaround I'm saving the image at the first possible moment when it renders on the screen then quickly dismiss it.

This is how I save the widget now :


class SomeWidget extends StatefulWidget {
  const SomeWidget({
    Key key,
  }) : super(key: key);

  @override
  _ShareCocktailMockState createState() => _ShareCocktailMockState();
}

class _SomeWidgetState extends State<SomeWidget>
    with AfterLayoutMixin<SomeWidget> {
  GlobalKey globalKey = GlobalKey();

  Future<void> _capturePng() async {
    RenderRepaintBoundary boundary =
        globalKey.currentContext.findRenderObject();
    try {
      if (boundary.debugNeedsPaint) {
        print("Waiting for boundary to be painted.");
        await Future.delayed(const Duration(milliseconds: 5));
        return _capturePng();
      }
    } catch (_) {}
    try {
      ui.Image image = await boundary.toImage();
      ByteData byteData =
          await image.toByteData(format: ui.ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();

      // SHARING IMAGE TO SOCIAL MEDIA
      // CODE

      // widget is presented with a dialog so I just pop it
      Navigator.of(context).pop();
    } catch (_) {
      await Future.delayed(const Duration(milliseconds: 5));
      return _capturePng();
    }
  }

  @override
  void afterFirstLayout(BuildContext context) {
    _capturePng();
  }

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      key: globalKey,
      child: SuperFancyWidget(),
    );
  }
}

afterFirstLayout is from https://pub.dev/packages/after_layout package

2 Answers

Okay if you want to save your widget as png picture, you can use the screenshot package. Wrap the widget like this:

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

Read Readme section for details in the package.

The screenshot package (https://pub.dev/packages/screenshot) has been updated to now support capturing a widget that isn't displayed on screen.

So something like below should work:

ScreenshotController screenshotController = ScreenshotController();
  late File customFile;
await screenshotController
              .captureFromWidget(CustomWidget())
              .then((capturedImage) async {
            await widgetToImageFile(capturedImage);
  Future<void> widgetToImageFile(
    Uint8List capturedImage,
  ) async {
    Directory tempDir = await getTemporaryDirectory();
    String tempPath = tempDir.path;
    final ts = DateTime.now().millisecondsSinceEpoch.toString();
    String path = '$tempPath/$ts.png';
    customFile = await File(path).writeAsBytes(capturedImage);
  }

Now you should have a custom file containing a .png of your widget to do with as you please.

Related