Yon*_*kee 2 loops dart flutter
我试图在列表的 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');
});
}
Run Code Online (Sandbox Code Playgroud)
知道我怎么做吗?
使用await Future.delayed()暂停某些时间和一个for循环,而不是forEach()
如果forEach()接收异步函数,则每个迭代调用将在单独的异步上下文中运行,这与并行代码执行类似。同时 forEach it self 将立即返回,而无需等待任何异步函数完成。
示例: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');
};
}
Run Code Online (Sandbox Code Playgroud)