Dartlang wait more than one future

2020-02-03 05:33发布

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?

标签: dart future
1条回答
▲ chillily
2楼-- · 2020-02-03 05:53

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

查看更多
登录 后发表回答