Eri*_*son 5 progress stream listen flutter dio
我有一个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
});
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的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.
*/
}
}
}
Run Code Online (Sandbox Code Playgroud)
Dio 文档提供了一个关于如何将响应类型转换为流/字节的示例。但是它没有给出任何关于如何在下载文件时执行此操作的示例。有人能指出我正确的方向吗?我现在真的很困惑..非常感谢你!
我正是这个问题
我解决了模型中的依赖注入问题
实际上,我在模型中定义了进度字段(双精度),用于监听下载百分比,并将模型中的一个对象定义到 GetX 控制器中(您可以使用任何依赖项注入,如 getIt,...),因此使用实时数据机制,这个问题将如此轻松地解决