首页 > 解决方案 > 页面更改后 Flutter Isolate ReceiverPort 未侦听

问题描述

我在 page1 上的 receiverPort 上添加了一个侦听器,并在另一个隔离上进行了更改,当我在第 1 页导航到第 2 页时,端口侦听和打印正常,即使没有取消/关闭它,端口也会停止侦听。

initDownloader() async{
ReceivePort receiverPort = ReceivePort();

 Directory appDocDir = await getApplicationDocumentsDirectory();
 String appDocPath = appDocDir.path;
 String downloadDirectory = appDocPath+'/venus/';

 IsolateNameServer.registerPortWithName(receiverPort.sendPort, 'downloader_send_port');
    receiverPort.listen((dynamic data) {
      //as you can see this is to be called every time there is a change in data, 
      //and works when I am inside the page stops printing on page 2
      print('on Receive from isolate ');
      String id = data[0];
      DownloadTaskStatus status = data[1];
      int progress = data[2];
      SendPort sendPort;
      if(data[3] != null){
        if(data[3] is SendPort){
          print('received message from port');
          sendPort = data[3];
          sendPort.send(downloadDirectory);

        }
      }

      //these are also not getting called on page 2
      print('Progress is $progress');
      print('Status is ${downloadTaskStatus.toString()}');

    });

    FlutterDownloader.registerCallback(downloadCallback);
  }


和 downloadCallBack (这是一个顶级函数)


void downloadCallback(String id, DownloadTaskStatus status, int progress){

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

  print('background call back : id $id status $status progress $progress');

  ReceivePort receivePort = ReceivePort();

  receivePort.listen((message) {
    if(message != null){
      //never reaches here after changing page
      print('received the download directory from main $message');
      encryptDownloads(message);
    }else {
      print('received null instead of downloadPath');
    }
  });


  if(status == DownloadTaskStatus.complete){
    print('download complete sending send port to main');//from here it prints and sends to the receiver port
    send.send([id, status, progress, receivePort.sendPort]);
  } else send.send([id, status, progress, null]);





}

  1. 为什么它在被取消之前停止收听?
  2. 当用户导航到其他页面时,有没有办法让它活着?

标签: flutterdart

解决方案


推荐阅读