如何避免通过foreach函数在dart

如何避免通过foreach函数在dart

本文介绍了如何避免通过foreach函数在dart Map中使用await键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个地图,它与使用内部项目的一些异步处理有关.我使用了 forEach 循环构造,并且回调内部被设计为异步,因为我在迭代主体内部调用了 await

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

我需要在迭代所有项目后调用 callFunc().但是 forEach 立即退出.帮助!

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

推荐答案

Map.entries 而不是 forEach.如果您处于异步函数中,则 for 循环体中的 await-ing 将暂停迭代.条目对象还允许您访问键和值.

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

这篇关于如何避免通过foreach函数在dart Map中使用await键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:20