downloadFileHelper function
Implementation
Future<DownloadResult?> downloadFileHelper(String url) async {
try {
final dir = await getApplicationDocumentsDirectory();
final fileName = Uri.parse(url).pathSegments.last;
final filePath = '${dir.path}/$fileName';
// ✅ Check if the cached file exists and is still valid
if (await _isCacheValid(filePath)) {
debugPrint('Using cached file: $filePath');
return (file: XFile(filePath), progress: Stream.value(100.0));
}
// 🔽 Create a StreamController to emit progress updates
final StreamController<double> progressController = StreamController<double>();
debugPrint('Downloading new file...');
await Dio().download(
url,
filePath,
onReceiveProgress: (count, total) {
double progress = (count / total) * 100;
progressController.add(progress);
},
);
// ✅ Save the timestamp of this download
await _saveCacheTimestamp(filePath);
// Close the stream after download completion
progressController.close();
return (file: File(filePath).existsSync() ? XFile(filePath) : null, progress: progressController.stream);
} catch (e) {
debugPrint('Error downloading file: $e');
return null;
}
}