[ACCEPTED]-Using Flutter Downloader plugin, after download app closes-flutter-packages

Accepted answer
Score: 22

Maybe it late but it may help others. Recently 13 I faced this error and I solved it. Your 12 UI is rendering in Main isolate and your 11 download events come from background isolate. Because 10 codes in callback are run in the background 9 isolate, so you have to handle the communication 8 between two isolates. Usually, communication 7 needs to take place to show download progress 6 in the main UI. Implement the below code 5 to handle communication:

import 'dart:isolate';
import 'dart:ui'; // You need to import these 2 libraries besides another libraries to work with this code

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 = data[1];
      int progress = data[2];
      setState((){ });
    });

    FlutterDownloader.registerCallback(downloadCallback);
  }

@override
  void dispose() {
    IsolateNameServer.removePortNameMapping('downloader_send_port');
    super.dispose();
  }

  static void downloadCallback(String id, DownloadTaskStatus status, int progress) {
    final SendPort send = IsolateNameServer.lookupPortByName('downloader_send_port')!;
    send.send([id, status, progress]);
  }


void _download(String url) async {
    final status = await Permission.storage.request();

    if(status.isGranted) {
      final externalDir = await getExternalStorageDirectory();

      final id = await FlutterDownloader.enqueue(
          url: url,
          savedDir: externalDir!.path,
        showNotification: true,
        openFileFromNotification: true,
      );
    } else {
      print('Permission Denied');
    }
  }

Call _download(url) function 4 in your button and you are ready to go.

N.B: I 3 am using sound null safety in my app and 2 for this reason I am using null aware operator 1 in this line of code:

final SendPort send = IsolateNameServer.lookupPortByName('downloader_send_port')!;

More Related questions