Flutter Dio软件包:如何收听另一个类的下载进度?

问题描述 投票:0回答:1

我有一个DownloadsService类,该类使用dio包处理文件的下载。我想听从ViewModel类中的下载进度,该类在downloadFile类中实现了DownloadService方法。我该怎么做呢?

这是我的DownloadsService类的代码段:

class DownloadsService {
   final String urlOfFileToDownload = 'http://justadummyurl.com/'; //in my actual app, this is user input
   final String filename = 'dummyfile.jpg';
   final String dir = 'downloads/$filename'; //i'll have it saved inside internal storage downloads directory

   void downloadFile() {
     Dio dio = Dio();
     dio.download(urlOfFileToDownload, '$dir/$filename', onReceiveProgress(received, total) {
        int percentage = ((received / total) * 100).floor(); //this is what I want to listen to from my ViewModel class
     });
   }
}

这是我的ViewModel类:

class ViewModel {
   DownloadsService _dlService = DownloadsService(); //note: I'm using get_it package for my services class to make a singleton instance. I just wrote it this way here for simplicity..

      void implementDownload() {

       if(Permission.storage.request().isGranted) { //so I can save the file in my internal storage
          _dlService.downloadFile();

        /*
         now this is where I'm stuck.. My ViewModel class is connected to my View - which displays
         the progress of my download in a LinearProgressIndicator. I need to listen to the changes in
         percentage inside this class.. Note: my View class has no access to DownloadsService class. 
       */

      }        
   }
}

Dio文档提供了有关如何将响应类型转换为流/字节的示例。但是,在下载文件时,它没有给出如何进行响应的示例。有人可以指出我正确的方向吗?此刻我真的很困。.非常感谢!

flutter stream progress listen dio
1个回答
0
投票

如果View创建了ViewModel,则必须在View类中定义PublishSubject变量,然后将其传递给ViewModel,并将其传递给DownloadsService作为参数

像这样:

class ViewModel {
       PublishSubject publishSubject;
       ViewModel(this.publishSubject);
       DownloadsService _dlService = DownloadsService();   
          void implementDownload() { 
           if(Permission.storage.request().isGranted) {  
              _dlService.downloadFile(publishSubject); 
          }        
       }
    }

以便View侦听在downloadFile方法之前将发生的更改,该方法又依次发送更改

像这样:

void downloadFile(PublishSubject publishSubject) {
     Dio dio = Dio();
     dio.download(urlOfFileToDownload, '$dir/$filename', 
        onReceiveProgress(received,total) {
        int percentage = ((received / total) * 100).floor(); 
        publishSubject.add(percentage);
     });
   }

以便该接口侦听之前将发生的更改

像这样:

class View {
  PublishSubject publishSubject = PublishSubject();
  ViewModel viewModel;
  View(){
    publishSubject.listen((value) {
      // the value is percentage.
      //can you refresh view or do anything
    });
   viewModel = ViewModel(publishSubject);
  }  
}
© www.soinside.com 2019 - 2024. All rights reserved.