[dart]颤抖着如何等待map.forEach在Future< void>中完成功能? [英] [dart]flutter how to wait map.forEach to complete in Future<void> function?

查看:237
本文介绍了[dart]颤抖着如何等待map.forEach在Future< void>中完成功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例代码

Map<String,String> gg={'gg':'abc','kk':'kojk'};

Future<void> secondAsync() async {
  await Future.delayed(const Duration(seconds: 2));
  print("Second!");
  gg.forEach((key,value) async{await Future.delayed(const Duration(seconds: 5));
  print("Third!");
});
}

Future<void> thirdAsync() async {
  await Future<String>.delayed(const Duration(seconds: 2));
  print('third');
}

void main() async {
  secondAsync().then((_){thirdAsync();});
}

输出

Second!
third
Third!
Third!

如您所见,我要等到地图的foreach循环完成后再打印third
预期产量

as you can see i want to use to wait until foreach loop of map complete to complete then i want to print third
expected Output

Second!
Third!
Third!
third

推荐答案

Map.forEach(类似地,Iterable.forEach)用于在集合的每个元素上执行一些代码,以消除副作用 .返回值将被忽略.因此,如果提供返回Future的函数,则该Future将会丢失,并且在完成时将不会通知您.

Map.forEach (and similarly, Iterable.forEach) is meant to execute some code on each element of a collection for side effects. The return values are ignored. Therefore if you supply a function that returns a Future, that Future is lost, and you will not be able to be notified when it completes.

不要在async回调中使用.forEach.

Don't use .forEach with async callbacks.

相反,如果要依次等待每个async回调 ,请使用常规的for循环:

Instead, if you want to wait for each async callback sequentially, just use a normal for loop:

for (var mapEntry in gg.entries) {
  await Future.delayed(const Duration(seconds: 5));
}

,或者如果您真的更喜欢使用.forEach语法,则可以使用Future.forEach:

or if you really prefer using .forEach syntax, you could use Future.forEach:

await Future.forEach([
  for (var mapEntry in gg.entries)
    Future.delayed(const Duration(seconds: 5)),
]);

如果要允许您的async回调可能并行运行,则可以使用Future.wait:

If you want to allow your async callbacks to possibly run in parallel, you can use Future.wait:

await Future.wait([
  for (var mapEntry in gg.entries)
    Future.delayed(const Duration(seconds: 5)),
]);

类似的问题:

  • Flutter async/await doesn't work inside forEach
  • My async call is returning before list is populated in forEach loop

这篇关于[dart]颤抖着如何等待map.forEach在Future&lt; void&gt;中完成功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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