gpt4 book ai didi

flutter - 如何等待 forEach 完成异步回调?

转载 作者:行者123 更新时间:2023-12-03 04:38:17 31 4
gpt4 key购买 nike

示例代码

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!
正如你所看到的,我想用来等待 map 的 foreach 循环完成然后我想打印 third预期输出
Second!
Third!
Third!
third

最佳答案

Iterable.forEach , Map.forEach , 和 Stream.forEach旨在对集合的每个元素执行一些代码以产生副作用。他们接受带有 void 的回调返回类型。因此,那些.forEach方法不能使用回调返回的任何值 ,包括返回 Future s。如果您提供一个返回 Future 的函数,那 Future将丢失,并且您将无法在完成时收到通知。因此,您不能等待每个迭代完成,也不能等待所有迭代完成。
请勿使用 .forEach带有异步回调。
相反,如果您想按顺序等待每个异步回调,只需使用普通的 for环形:

for (var mapEntry in gg.entries) {
await Future.delayed(const Duration(seconds: 5));
}
(一般来说, I recommend using normal for loops over .forEach 除特殊情况外,在所有情况下都是如此。 Effective Dart has a mostly similar recommendation。)
如果您真的更喜欢使用 .forEach语法并希望等待每个 Future依次使用 Future.forEach (确实期望回调返回 Future s):
await Future.forEach([
for (var mapEntry in gg.entries)
Future.delayed(const Duration(seconds: 5)),
]);
如果你想让你的异步回调可能并行运行,你可以使用 Future.wait :
await Future.wait([
for (var mapEntry in gg.entries)
Future.delayed(const Duration(seconds: 5)),
]);
https://github.com/dart-lang/linter/issues/891如果尝试将异步函数用作 Map.forEach,则请求分析器警告。或 Iterable.forEach回调(以及许多类似 StackOverflow 问题的列表)。

关于flutter - 如何等待 forEach 完成异步回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63719374/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com