Flutter:读取 BloC 状态的 Stream 数据,如果发生变化则重新渲染 UI

SiL*_*_Tz 5 state-management dart flutter bloc dio

我在使用 BloC 模式并结合使用 Dio 显示下载过程时遇到问题。

谁能告诉我,如何从 dio 获取 onUploadProgress 进入块状态并在状态内的进度更新时显示它?

目前我有 UI、BloC 和 API 类。我需要将我的块传递到 API 调用中以下载文件,然后添加一个额外的事件,如下所示:

onReceiveProgress: (int received, int total) => {
          bloc.add(DownloadingImages((received / total) * 100))
        });
Run Code Online (Sandbox Code Playgroud)

我还发现了一个大问题,但我不知道如何以干净的方式解决。如果我添加 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.");
}
Run Code Online (Sandbox Code Playgroud)

在用户界面中:

} 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);
          }
Run Code Online (Sandbox Code Playgroud)

我很想看到一个干净的解决方案来解决这个问题。