flutter - 我如何从Dart流中的回调函数产生值

标签 flutter dart

我在flutter应用程序中定义了以下流:

  static Stream<String> downloadIdentifiers() async* {
    try {
      yield "test";
      final directory = await getApplicationDocumentsDirectory();

      Response response;
      Dio dio = new Dio();
      response = await dio.download(
        MyConstants.identifiersUrl,
        join(directory.path, "identifiers.json"),
        onReceiveProgress: (int received, int total) {
          print("$received / $total");
        },
      );
      yield join(directory.path, "identifiers.json");
    } catch (ex) {
      throw ex;
    }
  }

我正在使用https://github.com/flutterchina/dio进行下载。

我想产生有关流下载进度的信息,但是onReceiveProgress上的回调仅将常规函数用作回调。

如何获取有关接收/总字节的信息以在Stream上产生?

谢谢!

最佳答案

感谢jamesdlin的答案。
我终于在他的帮助下做到了这一点:

  static Stream<String> downloadIdentifiers() async* {
    StreamController<String> streamController = new StreamController();
    try {
      final directory = await getApplicationDocumentsDirectory();

      Dio dio = new Dio();
      dio.download(
        MyConstants.identifiersUrl,
        join(directory.path, "identifiers.json"),
        onReceiveProgress: (int received, int total) {
          streamController.add("$received / $total");
          print("$received / $total");
        },
      ).then((Response response) {
        streamController.add("Download finished");
      })
      .catchError((ex){
        streamController.add(ex.toString());
      })
      .whenComplete((){
        streamController.close();
      });
      yield* streamController.stream;
    } catch (ex) {
      throw ex;
    }
  }

关于flutter - 我如何从Dart流中的回调函数产生值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56914571/

相关文章:

flutter - 如何在Flutter Web应用程序中进入全屏模式

redux - 如何在带有 Redux 的 Flutter 中显示 snacker(或推送另一个页面)?

android - Flutter 找不到连接的设备(虚拟设备)

flutter - 如何使底部导航栏带有数字和文本 flutter

dart - 为什么在空安全的Dart中使用 'var'声明的变量为空?

dart - 命名参数 'home' 未定义 Flutter

firebase - Flutter - 排序 Cloud Firestore

flutter - 在图像顶部添加文本并通过点击按钮分享图像

dart - Dart SDK在Raspberry Pi上构建失败

flutter - 如何在 flutter 中以两种不同尺寸保存图像选择器中的图像