Flutter-Dart:等待一个结局 [英] Flutter - Dart : wait a forEach ends

查看:102
本文介绍了Flutter-Dart:等待一个结局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用从Firebase数据库检索的每个节点中的数据来修改字符串,然后使用修改后的字符串(称为内容)编写文件。

I try to modify a string using data in each node I retrieve from Firebase database, and then to write a file with the modifed string (called "content").

这是我尝试的方法:

// Retrieve initial content from Firebase storage
var data = await FirebaseStorage.instance.ref().child("...").getData(1048576);
var content = new String.fromCharCodes(data);

// Edit content with each node from Firebase database
final response = await FirebaseDatabase.instance.reference().child('...').once();
response.value.forEach((jsonString) async {
     ...
     // cacheManager.getFile returns a Future<File>
     cacheManager.getFile(signedurl).then((file){ 
         // Modify content
         content=content.replaceAll('test',file.path);
     });
});

// Finally write the file with content
print("test");
final localfile = File('index.html');
await localfile.writeAsString(content);

结果:

测试显示在forEach结束之前。

"test" is shown before the forEach ends.

我发现我们可以在Dart中进行操作( https://groups.google.com/a/dartlang.org/forum/#!topic/misc/GHm2cKUxUDU ):

I found that we can do in Dart (https://groups.google.com/a/dartlang.org/forum/#!topic/misc/GHm2cKUxUDU) :


等待Future.forEach

await Future.forEach

但如果我这样做,则:等待Future.response.value.forEach(听起来有点奇怪)

but in my case if I do : await Future.response.value.forEach (sounds a bit weird)

然后我得到:


未找到字母:响应。
等待Future.response.value.forEach((jsonString)async {

Getter not found: 'response'. await Future.response.value.forEach((jsonString) async {

如何等待forEach结尾(内容修改),然后再写入具有新内容的文件?

How to wait that forEach ends (with "content" modified) before to write the file with new content?

有什么想法吗?

推荐答案

如果使用 for(... in)代替 forEach ,则可以使用异步 / 等待

If you use for(... in ) instead of forEach you can use async/await

Future someMethod() async {
  ...

  for(final jsonString in response.value) {
     ...
     // cacheManager.getFile returns a Future<File>
     cacheManager.getFile(signedurl).then((file){ 
         // Modify content
         content=content.replaceAll('test',file.path);
     });
  });
}

使用 forEach 调用立即为每个 jsonString 触发并在其中调用 await 起作用,但 forEach 的返回类型为 void ,这是无法等待的,只有 Future 可以。

With forEach the calls fire away for each jsonString immediately and inside it await works, but forEach has return type void and that can't be awaited, only a Future can.

这篇关于Flutter-Dart:等待一个结局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆