downloadMediaListToDevice static method

Future<Map<String, File>> downloadMediaListToDevice(
  1. List<MediaItem> items,
  2. FileCategory category,
  3. String conversationId, {
  4. OnMediaSaved? onMediaSaved,
})

Download and save media to persistent storage (not cache)

Implementation

static Future<Map<String, File>> downloadMediaListToDevice(
    List<MediaItem> items,
    FileCategory category,
    String conversationId, {
      OnMediaSaved? onMediaSaved, // optional callback to update UI
    }) async {
  final Map<String, File> savedFiles = {};

  final dir = await getApplicationDocumentsDirectory(); // ✅ persistent
  final subDir = '${category.name}/$conversationId';
  final targetFolder = Directory('${dir.path}/$subDir');

  if (!await targetFolder.exists()) {
    await targetFolder.create(recursive: true);
  }

  for (final item in items) {
    try {
      final uri = Uri.parse(item.fileUrl);
      final safeFileName = p.basename(uri.path);
      final filePath = '${targetFolder.path}/$safeFileName';
      final file = File(filePath);

      final response = await http.get(uri);
      if (response.statusCode == 200) {
        await file.writeAsBytes(response.bodyBytes);
        savedFiles[safeFileName] = file;
        if (kDebugMode) {
          print("✅ Downloaded and saved: $filePath");
        }

        // ✅ Notify UI
        if (onMediaSaved != null) {
          onMediaSaved(safeFileName, file);
        }
      } else {
        if (kDebugMode) {
          print("❌ Download failed: $safeFileName (status: ${response.statusCode})");
        }
      }
    } catch (e) {
      if (kDebugMode) {
        print("❌ Error saving file: ${item.fileUrl} - $e");
      }
    }
  }

  return savedFiles;
}