captureScreenshot method
Capture the boundary to PNG bytes. Full window when area is null;
otherwise crops to area (logical coordinates) via a
PictureRecorder pass. Returns null when the boundary is not yet
attached / sized.
Implementation
Future<Uint8List?> captureScreenshot({
double pixelRatio = 1.0,
Rect? area,
}) async {
final ro = captureKey.currentContext?.findRenderObject();
if (ro is! RenderRepaintBoundary) return null;
if (!ro.attached || !ro.hasSize) return null;
try {
final fullImage = await ro.toImage(pixelRatio: pixelRatio);
if (area == null) {
final byteData =
await fullImage.toByteData(format: ui.ImageByteFormat.png);
return byteData?.buffer.asUint8List();
}
final recorder = ui.PictureRecorder();
final canvas = ui.Canvas(recorder);
final src = Rect.fromLTWH(
area.left * pixelRatio,
area.top * pixelRatio,
area.width * pixelRatio,
area.height * pixelRatio,
);
final dst = Rect.fromLTWH(0, 0, area.width, area.height);
canvas.drawImageRect(fullImage, src, dst, ui.Paint());
final picture = recorder.endRecording();
final cropped = await picture.toImage(
area.width.toInt(),
area.height.toInt(),
);
final byteData =
await cropped.toByteData(format: ui.ImageByteFormat.png);
return byteData?.buffer.asUint8List();
} catch (_) {
return null;
}
}