returnScreenShotPngBytes method

Future<Uint8List?> returnScreenShotPngBytes({
  1. int retries = 100,
  2. WidgetTester? tester,
})

returnScreenShotPngBytes takes a screenshot of the child widget and returns the bytes of the png file.

Implementation

Future<Uint8List?> returnScreenShotPngBytes(
    {int retries = 100, WidgetTester? tester}) async {
  Uint8List? pngBytes;
  try {
    await Future.delayed(const Duration(milliseconds: 100), () async {
      RenderRepaintBoundary? boundary = screenKey.currentContext
          ?.findRenderObject() as RenderRepaintBoundary?;
      if (boundary == null) {
        return (Future.value(null));
      }
      if (boundary.debugNeedsPaint && retries > 0) {
        debugPrint("Waiting for boundary to be painted (retries left: "
            "${retries.toString()}).");
        if (tester != null) {
          await tester.pumpAndSettle();
        }
        await Future.delayed(const Duration(milliseconds: 500));
        return (await returnScreenShotPngBytes(
            retries: retries - 1, tester: tester));
      }
      ui.Image uIImage = await boundary.toImage();
      var byteData = await uIImage.toByteData(format: ImageByteFormat.png);
      pngBytes = byteData?.buffer.asUint8List();
    });
  } catch (e, st) {
    debugPrint("Warning: cannot get screenshot (retries left: "
        "${retries.toString()}): ${e.toString()} ${st.toString()}");
  }
  if (retries <= 0) {
    return (pngBytes);
  }
  if (pngBytes == null) {
    return (await returnScreenShotPngBytes(
        retries: retries - 1, tester: tester));
  }
  return (pngBytes);
}