'Can't print Flutter_downloader progress
I'm trying to use Flutter_downloader to make my app able to download some attachment file and it work just fine. So I make the Isolate into class to tidy things up and tried to use the progress so I can show the download progress in my UI but the progress stays at 0.
How to fix this ? The download work just fine.
Flutter Downloader Isolate Code:
class DownloaderIsolate {
//Callback for the Flutter_Downloader
static downloadCallback(String id, DownloadTaskStatus status, int progress) {
final SendPort send =
IsolateNameServer.lookupPortByName('downloader_send_port')!;
send.send([id, status, progress]);
}
static setupDownloaderPort({int? progress}) {
ReceivePort _port = ReceivePort();
IsolateNameServer.registerPortWithName(
_port.sendPort, 'downloader_send_port');
FlutterDownloader.registerCallback(DownloaderIsolate.downloadCallback);
_port.listen((dynamic data) {
String id = data[0];
DownloadTaskStatus status = data[1];
progress = data[2];
});
}
}
My UI Page Code:
int? progress = 0;
void initState(){
DownloaderIsolate.setupDownloaderPort(progress: progress);
}
Widget build(BuildContext context) {
//Some Parents Code
//Trying to show the progress in String
Text(progress.toString()),
//Also Trying to show the progress
Text('$progress'),
}
Solution 1:[1]
The problem might be that you need to "setState" in order for your UI to update, but you can't setState in your isolate class. You can try the following:
Flutter Downloader Isolate Code:
static setupDownloaderPort({required Function(int) updateProgress}) {
ReceivePort _port = ReceivePort();
IsolateNameServer.registerPortWithName(
_port.sendPort, 'downloader_send_port');
FlutterDownloader.registerCallback(DownloaderIsolate.downloadCallback);
_port.listen((dynamic data) {
String id = data[0];
DownloadTaskStatus status = data[1];
updateProgress(data[2]);
});
}
UI Page:
int? progress = 0;
void initState(){
DownloaderIsolate.setupDownloaderPort(updateProgress: (_p) {
progress = _p;
});
super.initState();
}
Widget build(BuildContext context) {
//Some Parents Code
//Trying to show the progress in String
Text(progress.toString()),
//Also Trying to show the progress
Text('$progress'),
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
