我有一个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 文档提供了如何将响应类型转换为流/字节的示例。但它没有提供任何示例说明如何在下载文件时执行此操作。有人能指出我正确的方向吗?我现在真的被困住了..非常感谢!