示例代码

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!

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

推荐答案

Iterable.forEachMap.forEachStream.forEach用于对side effects的集合的每个元素执行一些代码.他们接受返回类型为void的回调.因此,those 104 methods cannot use any values returned by the callbacks人,包括Future人返回.如果您提供了一个返回Future的函数,那么Future将丢失,并且在它完成时您将无法收到通知.因此,您不能等待每个迭代完成,也不能等待所有迭代完成.

Do NOT use 100 with asynchronous callbacks.

相反,如果您想等待每个异步回调sequentially,只需使用普通的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(does期望返回Futures的回调):

await Future.forEach(
  gg.entries,
  (entry) => Future.delayed(const Duration(seconds: 5)),
);

如果希望允许异步回调尽可能并行运行,可以使用Future.wait:

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

如果试图将异步函数用作Map.forEachIterable.forEach回调,请参阅https://github.com/dart-lang/linter/issues/891以获取analyzer警告请求(以及许多类似StackOverflow问题的列表).

Dart相关问答推荐

Dart 3.3接口字段类型升级不起作用

程序给出不准确的值

Dart/Flutter ffi(外部函数接口)本机回调,例如:sqlite3_exec

Flutter android 生成apk

AngularDart 可以直接路由到组件吗?

设置文本以匹配Flutter中的列宽

Flutter 扩展方法不起作用,它说undefined class和requires the extension-methods language feature

多级异步代码中的 Dart 错误

Angular 2,使用 body 作为根 Select 器,而不是 my-app

如何在 Flutter CustomPainter 中使用Bezier Curves绘制形状

如何在flatter中使用SQFlite更新数据库表

将Dart嵌入到应用程序中

Flutter 中 ChangeNotifier 的构建器小部件

在 Dart 中实现观察者模式

一个集合如何确定两个对象在dart中相等?

Dart:如何判断变量类型是否为字符串

pub 依赖和 dev_dependencies 有什么区别?

如何在 Dart 中执行相当于 setTimeout + clearTimeout 的操作?

如何在 Dart 中读取控制台输入/标准输入?

Dart中var和dynamic类型的区别?