Handle download progress via background isolates
masterDownload events are emitted from a background isolate, while your UI runs on the main isolate. To update your UI, you must use an IsolateNameServer to communicate between them.
Steps to implement:
- Create a
ReceivePortin your UI class. - Register the
SendPortwith a unique name usingIsolateNameServer.registerPortWithName. - Listen to the port to receive updates.
- Define a top-level or static callback function decorated with
@pragma('vm:entry-point')to prevent tree shaking in release mode. - In the callback, look up the
SendPortby name and send the data back to the main isolate.
ReceivePort _port = ReceivePort();
@override
void initState() {
super.initState();
IsolateNameServer.registerPortWithName(_port.sendPort, 'downloader_send_port');
_port.listen((dynamic data) {
String id = data[0];
DownloadTaskStatus status = DownloadTaskStatus.fromInt(data[1]);
int progress = data[2];
setState((){ });
});
FlutterDownloader.registerCallback(downloadCallback);
}
@override
void dispose() {
IsolateNameServer.removePortNameMapping('downloader_send_port');
super.dispose();
}
@pragma('vm:entry-point')
static void downloadCallback(String id, int status, int progress) {
final SendPort? send = IsolateNameServer.lookupPortByName('downloader_send_port');
send?.send([id, status, progress]);
}