captureAndDownload static method
Captures and downloads a screenshot in one step.
This is a convenience method that combines capture and downloadScreenshot.
Parameters:
key: The GlobalKey of the widget to capturefileName: Optional custom file name. Defaults to 'screenshot_timestamp.png'pixelRatio: The pixel ratio for capture quality. Defaults to 3.0captureDelay: Optional delay before capturing to allow animations to completeshouldShowDebugLogs: Enable debug logging. Defaults to falsefileSaverCallback: Required on web. Callback for file saving usingfile_saverpathProviderCallback: Required on native. Callback for file saving usingpath_provider
Returns: The result of downloadScreenshot
Example:
await SScreenshot.captureAndDownload(
_screenshotKey,
fileName: 'my_screenshot.png',
fileSaverCallback: kIsWeb ? (bytes, name) async {
await FileSaver.instance.saveFile(
name: name,
bytes: bytes,
ext: name.split('.').last,
mimeType: MimeType.png,
);
} : null,
pathProviderCallback: !kIsWeb ? (bytes, name) async {
final dir = await getApplicationDocumentsDirectory();
final file = File('${dir.path}/$name');
await file.writeAsBytes(bytes);
return file;
} : null,
);
Implementation
static Future<dynamic> captureAndDownload(
GlobalKey key, {
String? fileName,
double pixelRatio = 3.0,
Duration? captureDelay,
bool shouldShowDebugLogs = false,
Future<void> Function(List<int>, String)? fileSaverCallback,
Future<File> Function(List<int>, String)? pathProviderCallback,
}) async {
try {
final fileName_ =
fileName ?? 'screenshot_${DateTime.now().millisecondsSinceEpoch}.png';
// First capture as bytes
final bytes = await capture(
key,
config: ScreenshotConfig(
pixelRatio: pixelRatio,
resultType: ScreenshotResultType.bytes,
captureDelay: captureDelay,
shouldShowDebugLogs: shouldShowDebugLogs,
),
) as List<int>;
// Then download
return await downloadScreenshot(
bytes,
fileName: fileName_,
fileSaverCallback: fileSaverCallback,
pathProviderCallback: pathProviderCallback,
);
} catch (e) {
if (kDebugMode) {
debugPrint('Capture and download failed: $e');
}
if (e is ScreenshotException) {
rethrow;
}
throw ScreenshotException('Failed to capture and download screenshot', e);
}
}