CodeBlanks Logo Icon CodeBlanks

Future.wait

Learn parallel Futures with Future.wait.

Future.wait

To start many Futures in parallel and wait for all of them you use Future.wait. It takes a list of Futures and returns a list of values when all complete. Parallel work is much faster than sequential await.

Example: final result = await Future.wait([Future.value(1), Future.value(2), Future.value(3)]);. result is a List<int> holding [1, 2, 3]. The three Futures run in parallel; when all finish Future.wait completes. If one Future fails Future.wait also fails. Inside an async function you wait with await; you can also chain with .then.

Practice Your turn: wait in parallel

Mark Future<void> main() async. Wait for three parallel Futures with final result = await Future.wait([Future.value(1), Future.value(2), Future.value(3)]);. Then print the list with print(result).

Starter code

main.dart
void main() {
  // mark as async
  // wait for three Futures with Future.wait
  // print the result
}

Sample solution

main.dart
Future<void> main() async {
  final result = await Future.wait([Future.value(1), Future.value(2), Future.value(3)]);
  print(result);
}

Expected output

[1, 2, 3]

Parallel vs sequential

If you await three Futures one by one the total time is the sum of their durations. With Future.wait you start them in parallel and the total is the slowest one. If each Future takes 1 second, sequential takes 3 seconds, parallel takes 1 second.

So running independent tasks in parallel is a good habit. But be careful: dependent tasks cannot run in parallel; if the second waits for the first's result you must go sequential. Inside Future.wait every Future must have the same type; for different types you use a common supertype. On error one failing Future fails the whole Future.wait; with eagerError: false you can wait for the rest.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Future.wait

Question
final result = await ____([Future.value(1), Future.value(2)]);
Answer
final result = await Future.wait([Future.value(1), Future.value(2)]);

Explanation: Future.wait waits for parallel Futures.

2 Fastest way to wait for three independent Futures?

main.dart
final a = await Future.wait([
  Future.value(1),
  Future.value(2),
  Future.value(3),
]);
  • Sequential await
  • .then chain
  • Future.wait in parallel Correct answer
  • try/catch

Explanation: Future.wait runs in parallel; it is the fastest.

3 Match Future.wait

Term Meaning
Future.wait waits in parallel
List<Future> input list
List<T> output list
eagerError error behavior

All lessons in Beginner