downloadImage method

  1. @override
Future<String> downloadImage({
  1. XFile? pickedFile,
  2. String? imageSource,
})
override

Implementation

@override
Future<String> downloadImage({XFile? pickedFile, String? imageSource}) async {
  try {
    Uint8List? bytes;

    // 🔸 1. From picked file
    if (pickedFile != null) {
      bytes = await pickedFile.readAsBytes();
    }

    // 🔸 2. From image URL
    if (bytes == null && imageSource != null) {
      final response = await http.get(Uri.parse(imageSource));
      if (response.statusCode == 200) {
        bytes = response.bodyBytes;
      } else {
        return 'Failed to download image from URL.';
      }
    }

    if (bytes == null) return 'No image data to save.';

    // 🔸 3. Save image to platform-specific location
    final fileName = 'image_${DateTime.now().millisecondsSinceEpoch}.png';

    if (kIsWeb) {
      // ✅ Web
      await FileSaver.instance.saveFile(
        name: fileName,
        bytes: bytes,
        fileExtension: 'png',
        mimeType: MimeType.png,
      );
      return 'Image saved (Web).';
    }

    if (defaultTargetPlatform == TargetPlatform.android ||
        defaultTargetPlatform == TargetPlatform.iOS) {
      // ✅ Mobile
      final granted = await _requestGalleryPermission();
      if (!granted) return 'Gallery permission denied.';

      final result = await ImageGallerySaverPlus.saveImage(
        bytes,
        quality: 100,
        name: fileName,
      );
      final success =
          result['isSuccess'] == true || result['isSuccess'] == 'true';
      return success ? 'Image saved to gallery.' : 'Failed to save image.';
    }

    // ✅ Desktop
    await FileSaver.instance.saveFile(
      name: fileName,
      bytes: bytes,
      fileExtension: 'png',
      mimeType: MimeType.png,
    );
    return 'Image saved (Desktop).';
  } catch (e) {
    return 'Error saving image: $e';
  }
}