Flutter 如何从dart流中的回调函数中生成值

Flutter 如何从dart流中的回调函数中生成值,flutter,dart,Flutter,Dart,我在颤振应用程序中定义了以下流: static Stream<String> downloadIdentifiers() async* { try { yield "test"; final directory = await getApplicationDocumentsDirectory(); Response response; Dio dio = new Dio(); response = await

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

  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;
    }
  }
静态流下载标识符()异步*{
试一试{
产量“测试”;
最终目录=等待getApplicationDocumentsDirectory();
反应;
Dio Dio=新的Dio();
response=等待dio.download(
MyConstants.IdentifierURL,
join(directory.path,“identifiers.json”),
onReceiveProgress:(收到整数,总计整数){
打印(“$received/$total”);
},
);
产生连接(directory.path,“identifiers.json”);
}捕获(ex){
掷骰子;
}
}
我正在使用下载

我想将下载进度的信息输出到我的流中,但是
onReceiveProgress
上的回调函数只接受一个常规函数作为回调函数

如何获取流中要产生的接收/总字节的信息

谢谢大家!

谢谢你的回答。 在他的帮助下,我终于做到了:

  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;
    }
  }
静态流下载标识符()异步*{
StreamController StreamController=新的StreamController();
试一试{
最终目录=等待getApplicationDocumentsDirectory();
Dio Dio=新的Dio();
下载(
MyConstants.IdentifierURL,
join(directory.path,“identifiers.json”),
onReceiveProgress:(收到整数,总计整数){
streamController.add(“$received/$total”);
打印(“$received/$total”);
},
).然后((响应){
streamController.add(“下载完成”);
})
.catchError((例如){
streamController.add(例如toString());
})
.完成时(){
streamController.close();
});
产量*streamController.stream;
}捕获(ex){
掷骰子;
}
}
您可以使用,并直接向其中添加元素。