gpt4 book ai didi

Flutter Dio 封装 : How to listen to download progress from another class?

转载 作者:行者123 更新时间:2023-12-04 17:27:26 24 4
gpt4 key购买 nike

我有一个 DownloadsService使用 dio 处理文件下载的类包裹。我想听我的ViewModel的下载进度实现 downloadFile 的类我的内部方法 DownloadService类(class)。我该怎么做呢?

这是我的代码片段 DownloadsService类(class):

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

最佳答案

如果查看 创建 View 模型 ,那么你必须定义 PublishSubject 中的变量查看 类,然后将其传递给 View 模型 ,并将其传递给 下载服务作为参数

像这样 :

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

使 查看 监听之前会发生的变化 下载文件方法,依次发送更改

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

以便接口(interface)监听之前会发生的变化

像这样:
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);
}
}

关于Flutter Dio 封装 : How to listen to download progress from another class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62378341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com