flutter_downloader
flutter_downloader copied to clipboard
Actions after download is completed
Where do i process the downloaded file after download action is completed? For examples, if I download a .zip file, I'd want to write a function to extract the file right away. Where can I put the extract function? I tried to put function extract() in _bindBackgroundIsolate() and it worked, but only when I'm at the widget that contains _bindBackgroundIsolate(). If I'm at another widget, function extract() doesn't run at all
Edit: to be exact, i put function extract() inside port.listen to get the complete event. But as far as I know, port is define as a ReceivePort, and it is not a broadcast stream, so calling port.listen from another widget will not work
If you need to process download events elsewhere (i.e. outside of the _port.listen method) then you can send the update via a normal flutter stream to anywhere you want, ad that can also be a broadcast stream. For example:
IsolateNameServer.registerPortWithName(
_port.sendPort, 'downloader_send_port');
_port.listen((dynamic data) {
/// process incoming data by passing it to the callbacks
String taskId = data[0];
DownloadTaskStatus status = data[1];
if (finalStates.contains(status)) {
// we have reached an end point
if (_numberOfRunningTasks != null) _numberOfRunningTasks--;
_numberCompleted++;
// determine the appropriate callback
if (status == DownloadTaskStatus.complete) {
_updateStream.add(DownloadUpdate(taskId, DownloadState.downloaded));
return;
}
if (status == DownloadTaskStatus.failed) {
_updateStream
.add(DownloadUpdate(taskId, DownloadState.downloadError));
return;
}
if (status == DownloadTaskStatus.canceled) {
_updateStream.add(DownloadUpdate(taskId, DownloadState.canceled));
return;
}
}
});
@HSCT Do you got it?
This is a more complex use case.
I've successfully implemented it in my app. Here's a very rough description of what I do:
- I listen for download task updates using
ReceivePort.listen((data) => callback)
- When a
callback
is called, then I call FlutterDownloader.loadTasks() - I loop over tasks and when a task is successful, I take the path to the downloaded file and extract the zip archive.
I think that the example app should demonstrate it. I'll try to work on it during the holidays. Meanwhile, contributions are welcome :)