captureAndSaveScreenshot static method
Implementation
static Future<ScreenshotDetails?> captureAndSaveScreenshot(
GlobalKey key,
) async {
try {
RenderRepaintBoundary? boundary =
key.currentContext?.findRenderObject() as RenderRepaintBoundary?;
if (boundary != null) {
// No need for the delay; toImage() already waits for rendering
ui.Image image = await boundary.toImage(pixelRatio: 2.0);
final data = await image.toByteData(
format: ui.ImageByteFormat.png,
);
if (data == null) {
NLogger.e('Error: Could not convert image to byte data.');
return null;
}
final bytes = data.buffer.asUint8List(); // No need for toList()
final Directory cacheDir = await getTemporaryDirectory();
final String filePath =
'${cacheDir.path}/screenshot_${DateTime.now().millisecondsSinceEpoch}.png';
final File imageFile = File(filePath);
await imageFile.writeAsBytes(bytes);
final Size imageDimensions = Size(
image.width.toDouble(),
image.height.toDouble(),
);
NLogger.i('Screenshot saved to: $filePath');
NLogger.i('Screenshot dimensions: $imageDimensions');
return ScreenshotDetails(
filePath: filePath,
screenshotSize: imageDimensions,
);
} else {
NLogger.e('Error: Could not find RenderRepaintBoundary.');
return null;
}
} catch (e) {
NLogger.e('Error capturing and saving screenshot: $e');
return null;
}
}