How would I put a pause in a .forEach interation

♀尐吖头ヾ 提交于 2020-05-17 11:27:03

问题


I am attempting to put in a pause between a forEach loop for a list.

I would have thought the timeout would cause a pause for the loop but it just seems to start 3 timers all at once. (In very quick succession.)

  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?


回答1:


Use await Future.delayed() to pause for certain duration and a for loop, instead of forEach()

If forEach() receives async functions, each iteration call will run in a separate asynchronous context which can be reasoned about similarly to parallel code execution. Meanwhile forEach it self will return immediately without waiting until any async function to complete.

Async/await in List.forEach()

Sample: 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');
    };
  }


来源:https://stackoverflow.com/questions/54340205/how-would-i-put-a-pause-in-a-foreach-interation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!