[dart]flutter how to wait map.forEach to complete in Future<void> function?

情到浓时终转凉″ 提交于 2020-11-25 04:03:50

问题


sample code

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();});
}

output

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

回答1:


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.

Don't use .forEach with async callbacks.

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));
}

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)),
]);

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)),
]);

Similar questions:

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



回答2:


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) {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();});
}

``



回答3:


I believe you are looking for this.

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


来源:https://stackoverflow.com/questions/63719374/dartflutter-how-to-wait-map-foreach-to-complete-in-futurevoid-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!