Dart Future.wait()
Syntax & Examples
Future.wait() static-method
The `wait` static method in Dart waits for multiple futures to complete and collects their results.
Syntax of Future.wait()
The syntax of Future.wait() static-method is:
Future<List<T>> wait<T>(Iterable<Future<T>> futures, { bool eagerError: false, void cleanUp(T successValue) })
This wait() static-method of Future waits for multiple futures to complete and collects their results.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
futures | required | An iterable collection of futures. |
eagerError | optional | A boolean flag indicating whether to eagerly throw errors or wait for all futures to complete. |
cleanUp | optional | A function to clean up resources after each future completes successfully. |
Return Type
Future.wait() returns value of type Future<List<T>>
.
✐ Examples
1 Waiting for integer futures
In this example,
- We create two delayed futures with different durations and integer values.
- We use
Future.wait
to wait for both futures to complete and collect their results. - We print the collected results.
Dart Program
void main() async {
Future<int> future1 = Future.delayed(Duration(seconds: 2), () => 42);
Future<int> future2 = Future.delayed(Duration(seconds: 3), () => 84);
List<int> results = await Future.wait([future1, future2]);
print('Results: $results');
}
Output
Results: [42, 84]
2 Waiting for string futures
In this example,
- We create two delayed futures with different durations and string values.
- We use
Future.wait
to wait for both futures to complete and collect their results. - We print the collected results.
Dart Program
void main() async {
Future<String> future1 = Future.delayed(Duration(seconds: 3), () => 'Hello');
Future<String> future2 = Future.delayed(Duration(seconds: 2), () => 'World');
List<String> results = await Future.wait([future1, future2]);
print('Results: $results');
}
Output
Results: [Hello, World]
Summary
In this Dart tutorial, we learned about wait() static-method of Future: the syntax and few working examples with output and detailed explanation for each example.