Dart Future.any()
Syntax & Examples
Future.any() static-method
The `any` static method in Dart returns the result of the first future in a collection of futures to complete.
Syntax of Future.any()
The syntax of Future.any() static-method is:
Future<T> any<T>(Iterable<Future<T>> futures)
This any() static-method of Future returns the result of the first future in futures to complete.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
futures | required | An iterable collection of futures. |
Return Type
Future.any() returns value of type Future<T>
.
✐ Examples
1 Handling multiple futures
In this example,
- We create three delayed futures with different durations and values.
- We use
Future.any
to get the result of the first completed future. - We register a callback using
then
to print the value of the first completed future.
Dart Program
void main() {
Future<int> future1 = Future.delayed(Duration(seconds: 2), () => 42);
Future<int> future2 = Future.delayed(Duration(seconds: 3), () => 84);
Future<int> future3 = Future.delayed(Duration(seconds: 1), () => 126);
Future<int> firstCompleted = Future.any([future1, future2, future3]);
firstCompleted.then((value) {
print('First future completed with value: $value');
});
}
Output
First future completed with value: 126
2 Handling string futures
In this example,
- We create two delayed futures with different durations and string values.
- We use
Future.any
to get the result of the first completed future. - We register a callback using
then
to print the value of the first completed future.
Dart Program
void main() {
Future<String> future1 = Future.delayed(Duration(seconds: 3), () => 'Hello');
Future<String> future2 = Future.delayed(Duration(seconds: 2), () => 'World');
Future<String> firstCompleted = Future.any([future1, future2]);
firstCompleted.then((value) {
print('First future completed with value: $value');
});
}
Output
First future completed with value: World
Summary
In this Dart tutorial, we learned about any() static-method of Future: the syntax and few working examples with output and detailed explanation for each example.