我试图在列表的 forEach 循环之间暂停。
我原以为超时会导致循环暂停,但它似乎一次启动了 3 个计时器。 (非常快速地接连出现。)
startTimeout(int seconds) async {
print('Timer Being called now');
var duration = Duration(seconds: seconds);
Timer(duration, doSomething());
}
startDelayedWordPrint() {
List<String> testList = ['sfs','sdfsdf', 'sfdsf'];
testList.forEach((value) async {
await startTimeout(30000);
print('Writing another word $value');
});
}
Any idea how I might do this?
最佳答案
使用await Future.delayed()
暂停一段时间和一个 for 循环,而不是 forEach()
如果 forEach()
接收异步函数时,每个迭代调用都将在单独的异步上下文中运行,其推理类似于并行代码执行。同时 forEach 它自己将立即返回,而无需等待任何异步函数完成。
Async/await in List.forEach()
样本:
https://dartpad.dartlang.org/a57a500d4593aebe1bad0ed79376016c
main() async {
List<String> testList = ['sfs','sdfsdf', 'sfdsf'];
for(final value in testList) {
await Future.delayed(Duration(seconds: 1));
print('Writing another word $value');
};
}
关于loops - 我如何在 .forEach 迭代中暂停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54340205/