16

So, I have a map which has to do with some asynchronous processing using the items inside. I used the forEach loop construct and inside the callback is designed to be async because I call an await inside the iteration body

myMap.forEach((a, b) { await myAsyncFunc(); } );
callFunc();

I need the callFunc() to be called after all the items have been iterated. But the forEach exits immediately. Help!

4 Answers 4

36

Use a for loop over Map.entries instead of forEach. Provided you are in an async function, await-ing in the body of a for loop will pause the iteration. The entry object will also allow you to access both the key and value.

Future<void> myFunction() async {
  for (var entry in myMap.entries) {
    await myAsyncFunction(entry.key, entry.value);
  }
  callFunc();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hmmm ok, looks like it'll work, but I require both key and value, the reason why I had to use a map in the first place.
Edited - the entry gives you the key and the value. If you have requirements like that it is easier to give them in your question then later in comments
Yep, I am new to dart and Flutter, and also the myMap should actually be myMap.entries in your code. Thanks, it worked.
18

You can also use Future.forEach with a map like this :

await Future.forEach(myMap.entries, (MapEntry entry) async {
  await myAsyncFunc();          
});
callFunc();

1 Comment

This should be accepted answer as it does use forEach instead of for loop. Thanks Jordan!
12

You could also use map like:

const futures = myMap.map((a, b) => myAsyncFunc());
await Future.wait(futures);
callFunc();

4 Comments

Thanks for answer. However I got what I required from the selected answer. Cheers!
@VijayKumarKanta You're welcome. Keep in mind the result is slightly different. While my answer starts all the async work at once and awaits for all at the end, the other answer starts each one and awaits it before starting the next one.
I think your solution is a bit nicer and performance effective. I think it should be used instead. However Im not changing answer selection though. Thanks a lot!
No problem. Wasn't asking to :)
1

entries used in extract Maplist from HashMap.

 products.entries.forEach((e) {
  var key = e.key;
  var values = e.value;
    double sum = 0;
    values.forEach((value) => sum += value[PlanogramShelf.SHELF_FULL]);
    target.add(OrdinalSales(
        key, double.parse((sum / valueslength).toStringAsFixed(2))));
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.