captureAndDownload static method

Future captureAndDownload(
  1. GlobalKey<State<StatefulWidget>> key, {
  2. String? fileName,
  3. double pixelRatio = 3.0,
  4. Duration? captureDelay,
  5. bool shouldShowDebugLogs = false,
  6. Future<void> fileSaverCallback(
    1. List<int>,
    2. String
    )?,
  7. Future<File> pathProviderCallback(
    1. List<int>,
    2. String
    )?,
})

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 capture
  • fileName: Optional custom file name. Defaults to 'screenshot_timestamp.png'
  • pixelRatio: The pixel ratio for capture quality. Defaults to 3.0
  • captureDelay: Optional delay before capturing to allow animations to complete
  • shouldShowDebugLogs: Enable debug logging. Defaults to false
  • fileSaverCallback: Required on web. Callback for file saving using file_saver
  • pathProviderCallback: Required on native. Callback for file saving using path_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);
  }
}