downloadFile function
Implementation
Future<DownloadTaskForAll> downloadFile(String url, {File? file}) async {
var task = DownloadTaskForAll(targetFile: file);
var httpClient = Client();
var request = Request('GET', Uri.parse(url));
var response = await httpClient.send(request);
List<List<int>> chunks = [];
int downloaded = 0;
int sayac = 0;
task.setDownloadingStream = response.stream.listen((List<int> chunk) {
if (sayac % 500 == 0) {
task.updateTask(ProcessTask(
processed: downloaded,
total: response.contentLength!,
state: TaskState.running));
}
chunks.add(chunk);
downloaded += chunk.length;
sayac++;
}, onDone: () {
double percentage = (downloaded / response.contentLength!);
Uint8List? bytes;
if (percentage == 1) {
bytes = Uint8List(response.contentLength!);
int offset = 0;
for (List<int> chunk in chunks) {
bytes.setRange(offset, offset + chunk.length, chunk);
offset += chunk.length;
}
task.updateTask(ProcessTask(
processed: downloaded,
total: response.contentLength!,
state: TaskState.success,
bytes: bytes));
}
}, onError: (e, stackTrace) {
task.addError(e, stackTrace);
});
return task;
}