takeScreenshot method

Future<Image?> takeScreenshot(
  1. GlobalKey<State<StatefulWidget>> previewContainer,
  2. int originalSize
)

takes screenshot of the widget and returns Image

Implementation

Future<Image?> takeScreenshot(
    GlobalKey previewContainer, int originalSize) async {
  final currentContext = previewContainer.currentContext;
  if (currentContext == null) {
    return null;
  }
  RenderRepaintBoundary boundary =
      currentContext.findRenderObject() as RenderRepaintBoundary;
  double pixelRatio = originalSize / MediaQuery.of(currentContext).size.width;
  ui.Image image = await boundary.toImage(pixelRatio: pixelRatio);
  ByteData? byteData =
      await (image.toByteData(format: ui.ImageByteFormat.png));
  Uint8List pngBytes = byteData!.buffer.asUint8List();
  return Image.memory(pngBytes.buffer.asUint8List());
}