The `any` static method in Dart returns the result of the first future in a collection of futures to complete.
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.
Parameter | Optional/Required | Description |
---|---|---|
futures | required | An iterable collection of futures. |
Future.any() returns value of type Future<T>
.
In this example,
Future.any
to get the result of the first completed future.then
to print the value of the first completed future.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');
});
}
First future completed with value: 126
In this example,
Future.any
to get the result of the first completed future.then
to print the value of the first completed future.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');
});
}
First future completed with value: World
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.