captureAsUiImage method

Future<Image?> captureAsUiImage({
  1. double? pixelRatio = 1,
  2. Duration delay = const Duration(milliseconds: 20),
})

Implementation

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 Future.delayed(delay, () async {
    try {
      final findRenderObject =
          _containerKey.currentContext?.findRenderObject();

      print(containerKey.currentContext);
      print(_containerKey.currentContext?.findRenderObject());
      if (findRenderObject == null) {
        return null;
      }

      final boundary = findRenderObject as RenderRepaintBoundary;
      final context = _containerKey.currentContext;
      var pixelRatioValue = pixelRatio;
      if (pixelRatio == null) {
        if (context != null) {
          pixelRatioValue =
              pixelRatio ?? MediaQuery.of(context).devicePixelRatio;
        }
      }
      final image = await boundary.toImage(pixelRatio: pixelRatioValue ?? 1);
      return image;
    } catch (exception) {
      _logger.severe('Failed to capture screenshot: $exception');
    }
    return null;
  });
}