我在使用 BloC 模式并结合使用 Dio 显示下载过程时遇到问题。
谁能告诉我,如何让 dio 的 onUploadProgress 进入一个 bloc 状态并在状态内的进度更新时显示它?
目前我有 UI、BloC 和一个 API 类。我需要将我的 bloc 传递给 API 调用以下载文件,然后添加一个额外的事件,如下所示:
onReceiveProgress: (int received, int total) => {
bloc.add(DownloadingImages((received / total) * 100))
});
我还发现了一个大问题,我不知道如何以干净的方式解决。如果我添加 DownloadingImage 状态并传递该过程,它不会更新 UI。发生这种情况是因为状态没有改变,只是其中的值。BlocBuilder 无法识别状态内的值变化,也不会重新渲染 UI ...
所以我有另一个解决方法(BloC):
if (state is ImagesDownloading) {
imageBloc.add(DownloadingImages2(state.progress));
if (state.progress < 100) {
return DownloadAndProgressWidget(
done: false, progress: state.progress);
} else {
return DownloadAndProgressWidget(done: true, progress: 100);
}
} else if (state is ImagesDownloading) {
imageBloc.add(DownloadingImages2(state.progress));
if (state.progress < 100) {
return DownloadAndProgressWidget(
done: false, progress: state.progress);
} else {
return DownloadAndProgressWidget(done: true, progress: 100);
}
ImageState _downloadImages(String localPath) {
try {
api.fetchLibraryImagesFromBackend(localPath, this);
return ImagesDownloading(0);
// Update the ui later from here to show progress.
// Get the progress and pass it to downloading when 100% is reached return ImagesDownloaded state
} on ImagesError {
return ImagesError("Couldn't download images.");
}
在用户界面中:
} else if (state is ImagesDownloading) {
imageBloc.add(DownloadingImages2(state.progress));
if (state.progress < 100) {
return DownloadAndProgressWidget(
done: false, progress: state.progress);
} else {
return DownloadAndProgressWidget(done: true, progress: 100);
}
} else if (state is ImagesDownloading) {
imageBloc.add(DownloadingImages2(state.progress));
if (state.progress < 100) {
return DownloadAndProgressWidget(
done: false, progress: state.progress);
} else {
return DownloadAndProgressWidget(done: true, progress: 100);
}
我很想看到一个干净的解决方案来解决这个问题。