downloadAndCacheMedia static method
Downloads media once and returns its local path.
Implementation
static Future<String?> downloadAndCacheMedia(
String mediaUrl, {
String? cacheSubdirectory,
String? fileNamePrefix,
}) async {
try {
final mediaType = _getMediaType(mediaUrl);
final extension = _extractExtension(mediaUrl, mediaType);
final cacheDirectory = await _getCacheDirectory(cacheSubdirectory);
final prefix = fileNamePrefix ?? 'media';
final file = File('${cacheDirectory!.path}/${_buildFileName(mediaUrl, prefix, extension)}');
if (await file.exists()) {
return file.path;
}
debugLog('Downloading ${mediaType.name} from: $mediaUrl');
final response = await _dio.get<List<int>>(
mediaUrl,
options: Options(responseType: ResponseType.bytes),
);
final bytes = response.data;
if (response.statusCode == 200 && bytes != null && bytes.isNotEmpty) {
await file.writeAsBytes(bytes, flush: true);
return file.path;
}
debugLog(
'Failed to download ${mediaType.name}. '
'Status: ${response.statusCode}, bytes: ${bytes?.length ?? 0}',
);
return null;
} on DioException catch (e) {
debugLog('Dio error downloading media: ${e.type} ${e.message}');
return null;
} catch (e) {
debugLog('Error downloading media: $e');
return null;
}
}