如何在dart中从流中的回调函数产生值

时间:2019-07-06 13:32:39

标签: 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上的回调仅采用常规函数作为回调。

如何获取流中接收到的/总字节数的信息?

谢谢!

1 个答案:

答案 0 :(得分:0)

感谢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;
    }
  }