问题
I have a problem with using the BloC pattern in combination with showing a download process using Dio.
Can anybody tell me, how to get the onUploadProgress from dio into a bloc state and display it when the progress inside the state updates?
At the moment I have the UI, the BloC and an API class. I need to pass my bloc into the API call to download a file and then add an extra event like so:
onReceiveProgress: (int received, int total) => {
bloc.add(DownloadingImages((received / total) * 100))
});
Also there is a big problem I found and I don't know how to solve in a clean way. If I add the DownloadingImage state and pass on the process, it does not update the UI. That happens because the state does not change and just the value inside it.The BlocBuilder does not recognize the value change inside the state and will not re-render the UI...
So I have another workaround (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.");
}
In the UI:
} 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);
}
I would love to see a clean solution for that problem.
来源:https://stackoverflow.com/questions/61244262/flutter-read-the-stream-data-of-a-bloc-state-and-re-render-the-ui-if-it-changes