Dartlang wait more than one future

DartFuture

Dart Problem Overview


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 Solutions


Solution 1 - Dart

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

Solution 2 - Dart

Existing answer gives enough information, but I want to add a note/warning. As stated in the docs:

> The value of the returned future will be a list of all the values that were produced in the order that the futures are provided by iterating futures.

So, that means that the example below will return 4 as the first element (index 0), and 2 as the second element (index 1).

import 'dart:async';

Future main() async {
  print('start');

  List<int> li = await Future.wait<int>([
    fetchLong(),  // longer (which gives 4) is first
    fetchShort(), // shorter (which gives 2) is second
  ]);

  print('results: ${li[0]} ${li[1]}'); // results: 4 2
}

Future<int> fetchShort() {
  return Future.delayed(Duration(seconds: 3), () {
    print('Short!');
    return 2;
  });
}

Future<int> fetchLong() {
  return Future.delayed(Duration(seconds: 5), () {
    print('Long!');
    return 4;
  });
}

Solution 3 - Dart

If you want to wait for multiple futures of different types and also support null-safety then you can add a helper function similar to the following.

import 'package:tuple/tuple.dart';

Future<Tuple2<T1, T2>> waitConcurrently<T1, T2>(
    Future<T1> future1, Future<T2> future2) async {
  late T1 result1;
  late T2 result2;

  await Future.wait([
    future1.then((value) => result1 = value),
    future2.then((value) => result2 = value)
  ]);

  return Future.value(Tuple2(result1, result2));
}

In order for this to work you need tuples. At the moment Dart does not provide tuples natively, but there is a package from Google which does: https://pub.dev/packages/tuple

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbitnickView Question on Stackoverflow
Solution 1 - DartGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - DartAleksandarView Answer on Stackoverflow
Solution 3 - DartTobias MarschallView Answer on Stackoverflow