toPng static method

Future<Uint8List?> toPng(
  1. GlobalKey<State<StatefulWidget>> key, {
  2. double pixelRatio = 2.0,
})

Capture the widget attached to key as PNG bytes.

pixelRatio controls resolution (1.0 = screen pixels, 2.0 = 2× for retina).

Implementation

static Future<Uint8List?> toPng(
  GlobalKey key, {
  double pixelRatio = 2.0,
}) async {
  if (!_isValidPixelRatio(pixelRatio)) return null;
  try {
    final boundary =
        key.currentContext?.findRenderObject() as RenderRepaintBoundary?;
    if (boundary == null) return null;
    final image = await boundary.toImage(pixelRatio: pixelRatio);
    final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    return byteData?.buffer.asUint8List();
  } catch (e) {
    debugPrint('ChartExporter.toPng error: $e');
    return null;
  }
}