startDownload method
Starts a file download operation in the background.
The download continues even if the app moves to the background. Progress can be tracked using getDownloadProgress.
Parameters:
fileUrl: The URL of the file to downloadsavePath: Local path where the downloaded file should be savedheaders: Optional HTTP headers to include in the request
Returns a task ID string that can be used to track progress or cancel the task.
Throws an Exception if the download fails to start.
Implementation
@override
Future<String> startDownload({
required String fileUrl,
required String savePath,
Map<String, String>? headers,
}) async {
final taskId = DateTime.now().toIso8601String();
_taskDetails[taskId] = {
'type': 'download',
'url': fileUrl,
'path': savePath,
'createdAt': DateTime.now().toIso8601String(),
};
_progressControllers[taskId] = StreamController<double>();
_currentProgress[taskId] = 0.0;
await _enqueueOperation(() {
// Simulate download progress
Timer.periodic(const Duration(milliseconds: 100), (timer) {
final controller = _progressControllers[taskId];
if (controller == null || controller.isClosed) {
timer.cancel();
_operationComplete();
return;
}
double progress = 0.0;
controller.addStream(Stream.periodic(
const Duration(milliseconds: 100),
(count) {
progress = (count + 1) / 10;
_updateProgress(taskId, progress);
if (progress >= 1.0) {
timer.cancel();
_completedTasks[taskId] = true;
_createMockFile(savePath);
_operationComplete();
}
return progress;
},
).take(10));
});
});
return taskId;
}