Dartlang wait more than one future

bitnick picture bitnick · Feb 11, 2017 · Viewed 19.3k times · Source

I want to do something after a lot of future function done,bu I do not know how to write the code in dart? the code like this:

for (var d in data) {
  d.loadData().then()
}
// when all loaded
// do something here

but I don't want to wait them one by one:

for (var d in data) {
  await d.loadData(); // NOT NEED THIS
}

how to write those code in dart?

Answer

Günter Zöchbauer picture Günter Zöchbauer · Feb 11, 2017

You can use Future.wait to wait for a list of futures:

import 'dart:async';

Future main() async {
  var data = [];
  var futures = <Future>[];
  for (var d in data) {
    futures.add(d.loadData());
  }
  await Future.wait(futures);
}

DartPad example