[dart]颤抖着如何等待map.forEach在Future< void>中完成功能? [英] [dart]flutter how to wait map.forEach to complete in Future<void> function?
问题描述
示例代码
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< void>中完成功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!