Unable to take screenshot in V2 Flutter using native code, it was working well in V1 Flutter Unable to take screenshot in V2 Flutter using native code, it was working well in V1 Flutter flutter flutter

Unable to take screenshot in V2 Flutter using native code, it was working well in V1 Flutter


You can look at how the Screenshoot package code on its GitHub is doing it. The package is up-to-date to Flutter v2.

The package uses:

  • Gets the render object of the current widget thanks to GlobalKey. GlobalKey _containerKey = GlobalKey().currentContext?.findRenderObject();
  • Then it converts to RenderRepaintBoundary. RenderRepaintBoundary boundary = findRenderObject as RenderRepaintBoundary;
  • It gets the pixel ratio of the device. pixelRatio = pixelRatio ?? MediaQuery.of(context).devicePixelRatio;
  • Finally, it creates the image. ui.Image image = await boundary.toImage(pixelRatio: pixelRatio ?? 1);

See the whole code below:

Future<ui.Image?> captureAsUiImage(      {double? pixelRatio: 1,      Duration delay: const Duration(milliseconds: 20)}) {    //Delay is required. See Issue https://github.com/flutter/flutter/issues/22308    return new Future.delayed(delay, () async {      try {        var findRenderObject =            this._containerKey.currentContext?.findRenderObject();        if (findRenderObject == null) {          return null;        }        RenderRepaintBoundary boundary =            findRenderObject as RenderRepaintBoundary;        BuildContext? context = _containerKey.currentContext;        if (pixelRatio == null) {          if (context != null)            pixelRatio = pixelRatio ?? MediaQuery.of(context).devicePixelRatio;        }        ui.Image image = await boundary.toImage(pixelRatio: pixelRatio ?? 1);        return image;      } catch (Exception) {        throw (Exception);      }    });  }