CodeBlanks Logo Icon CodeBlanks

Future.wait

Learn parallel Futures with Future.wait.

Future.wait

Future.wait runs multiple Futures in parallel and waits for all of them. The result is a list containing the results of each Future.

Example: var results = await Future.wait([Future.value('A'), Future.value('B'), Future.value('C')]);. Three Futures start in parallel; await waits for all. results is a List: ['A', 'B', 'C'].

This method speeds up independent operations. If three network requests each take 1 second, running them in parallel takes 1 second total.

Parallel execution

Future.wait starts all Futures in the list at the same time. Each completes independently; Future.wait waits until all are done. The result list is ordered by the Future order.

Example: three Futures take 3, 1 and 2 seconds. With Future.wait they all start in parallel; total time is the longest, 3 seconds. Sequentially it would take 6 seconds.

In the result list each Future's result sits at its own index. results[0] gives the first Future's result.

Practice Wait for three Futures in parallel

void main() async is already written. Pass three Future.value ('A', 'B', 'C') to Future.wait. Wait with await and print the result with print.

Starter code

main.dart
void main() async {
  // run three Futures in parallel with Future.wait
  // wait and print the result
}

Sample solution

main.dart
void main() async {
  var results = await Future.wait([
    Future.value('A'),
    Future.value('B'),
    Future.value('C'),
  ]);
  print(results);
}

Expected output

[A, B, C]

Questions and answers

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

1 What does Future.wait return?

main.dart
var r = await Future.wait([
  Future.value('A'),
  Future.value('B'),
]);
  • A list of results Correct answer
  • void
  • It throws
  • A single value

Explanation: Future.wait returns a list containing the result of each Future.

2 The Future.wait call

Question
var results = await ____([Future.value('A'), Future.value('B'), Future.value('C')]);
Answer
var results = await Future.wait([Future.value('A'), Future.value('B'), Future.value('C')]);

Explanation: Future.wait waits for parallel Futures.

3 Match the Future.wait parts

Term Meaning
Future.wait([...]) Parallel wait
await Wait for completion
results Result list
results[0] First result

All lessons in Intermediate