captureScreen method

Future<bool> captureScreen(
  1. GlobalKey<State<StatefulWidget>> repaintKey, {
  2. String? customName,
  3. int? quality,
  4. List<Map<String, dynamic>>? customSizes,
  5. dynamic onError(
    1. String error
    )?,
})

Capture the current screen and store it locally

Implementation

Future<bool> captureScreen(
  GlobalKey repaintKey, {
  String? customName,
  int? quality,
  List<Map<String, dynamic>>? customSizes,
  Function(String error)? onError,
}) async {
  // Prevent multiple simultaneous captures
  if (_isCaptureProcessing) return false;
  _isCaptureProcessing = true;

  try {
    final config = ScreenshotConfig();
    final screenName = customName ?? config.fileNamePrefix;
    final imageQuality = quality ?? config.imageQuality;
    final screenSizes = customSizes ?? config.screenSizes;

    debugPrint('📸 Starting screen capture: "$screenName"...');

    // 1. Capture Image from RepaintBoundary
    final renderObject = repaintKey.currentContext?.findRenderObject();
    if (renderObject == null || renderObject is! RenderRepaintBoundary) {
      _handleError('Could not find RenderRepaintBoundary', onError);
      return false;
    }

    final boundary = renderObject;
    final ui.Image image = await boundary.toImage(pixelRatio: 2.0);
    final ByteData? byteData =
        await image.toByteData(format: ui.ImageByteFormat.png);

    if (byteData == null) {
      _handleError('Failed to get ByteData from image', onError);
      return false;
    }

    final Uint8List pngBytes = byteData.buffer.asUint8List();
    debugPrint('📸 Captured raw image: ${pngBytes.length} bytes');

    // 2. Process Image (Resize & Encode) in Background Isolate
    debugPrint('📸 Processing images in background isolate...');
    final ImageProcessor processor = ImageProcessor();
    final List<ScreenshotData> screenshots = await processor.processImage(
      pngBytes: pngBytes,
      screenName: screenName,
      screenSizes: screenSizes,
      imageQuality: imageQuality,
    );

    if (screenshots.isEmpty) {
      _handleError('Failed to process screenshots (list is empty)', onError);
      return false;
    }

    // 3. Store results
    // Create a timestamp for this group of images (using the one from the first screenshot or now)
    final captureId = screenshots.first.group;

    // Store the group of captures
    _captureGroups[captureId] = screenshots;

    // Add to the main list of all screenshots
    _allScreenshots.addAll(screenshots);

    debugPrint(
        '📸 Stored ${screenSizes.length} images. Total: ${_allScreenshots.length} in ${_captureGroups.length} groups');

    _isCaptureProcessing = false;
    return true;
  } catch (e) {
    debugPrint('❌ ERROR capturing screen: $e');
    _handleError(e.toString(), onError);
    _isCaptureProcessing = false;
    return false;
  }
}