Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

flutter - How to wait for forEach to complete with asynchronous callbacks?

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
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Iterable.forEach, Map.forEach, and Stream.forEach are meant to execute some code on each element of a collection for side effects. They take callbacks that have a void return type. Consequently, those .forEach methods cannot use any values returned by the callbacks, including returned Futures. If you supply a function that returns a Future, that Future will be lost, and you will not be able to be notified when it completes. You therefore cannot wait for each iteration to complete, nor can you wait for all iterations to complete.

Do NOT use .forEach with asynchronous callbacks.

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

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

(In general, I recommend using normal for loops over .forEach in all but special circumstances. Effective Dart has a mostly similar recommendation.)

If you really prefer using .forEach syntax and want to wait for each Future in succession, you could use Future.forEach (which does expect callbacks that return Futures):

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

If you want to allow your asynchronous 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)),
]);

See https://github.com/dart-lang/linter/issues/891 for a request for an analyzer warning if attempting to use an asynchronous function as a Map.forEach or Iterable.forEach callback (and for a list of many similar StackOverflow questions).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...