Using loops with Futures in Dart Using loops with Futures in Dart dart dart

Using loops with Futures in Dart


When you need to wait for multiple Futures to complete and you don't care about the order, you can use Future.wait():

Future.wait(files.map(functionThatReturnsAFuture))  .then((List response) => print('All files processed'));

If order is important you can use Future.forEach() instead which waits for each Future to be completed before moving to the next element:

Future.forEach(files, functionThatReturnsAFuture)  .then((response) => print('All files processed'));


Dart supports async/await since quite some time which allows it to write as

someFunc() async {  for(File file in files) {    await functionThatReturnsAFuture(file);  }}


This library can help https://pub.dartlang.org/packages/heavylist

HeavyList<File> abc = new HeavyList<File>([new File(), new File(), ]);abc.loop(new Duration(seconds: 1), (List<File> origin) {print(origin);}, (File item, Function resume) {  //simulating an asynchronous call  print(item);  //move to next item  resume();});