capture static method

Future<Map<String, dynamic>> capture()

Captures the current frame as PNG.

Returns a map with:

  • format: always "png"
  • width: logical width in points
  • height: logical height in points
  • pixel_ratio: device pixel ratio
  • base64: base64-encoded PNG image

On error returns {"error": "<reason>"}.

Implementation

static Future<Map<String, dynamic>> capture() async {
  try {
    // Get the root RenderView
    final renderViews = WidgetsBinding.instance.renderViews;
    if (renderViews.isEmpty) {
      return {'error': 'no_render_view'};
    }
    final renderView = renderViews.first;

    // debugLayer is null in release mode (Flutter does not maintain the layer tree)
    final layer = renderView.debugLayer;
    if (layer == null || layer is! OffsetLayer) {
      return {'error': 'not_available_in_release'};
    }

    final pixelRatio = renderView.flutterView.devicePixelRatio;
    final logicalSize = renderView.size;

    // Render the layer to an in-memory image
    final image = await layer.toImage(
      Offset.zero & logicalSize,
      pixelRatio: pixelRatio,
    );

    // Convert to PNG
    final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    image.dispose();

    if (byteData == null) {
      return {'error': 'capture_failed'};
    }

    final base64 = base64Encode(byteData.buffer.asUint8List());

    return {
      'format': 'png',
      'width': logicalSize.width.toInt(),
      'height': logicalSize.height.toInt(),
      'pixel_ratio': pixelRatio,
      'base64': base64,
    };
  } catch (e) {
    return {'error': e.toString()};
  }
}