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

ParameterOptional/RequiredDescription
futuresrequiredAn iterable collection of futures.

Return Type

Future.any() returns value of type Future<T>.



✐ Examples

1 Handling multiple futures

In this example,

  1. We create three delayed futures with different durations and values.
  2. We use Future.any to get the result of the first completed future.
  3. 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,

  1. We create two delayed futures with different durations and string values.
  2. We use Future.any to get the result of the first completed future.
  3. 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.