我在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/