Dart Future whenComplete()
Syntax & Examples

Future.whenComplete() method

The `whenComplete` method in Dart registers a function to be called when a future completes, regardless of whether it completes with a value or an error.


Syntax of Future.whenComplete()

The syntax of Future.whenComplete() method is:

 Future<T> whenComplete(FutureOr action()) 

This whenComplete() method of Future registers a function to be called when this future completes.

Parameters

ParameterOptional/RequiredDescription
actionrequiredA function to be called when the future completes, with no arguments.

Return Type

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



✐ Examples

1 Handling completion with value

In this example,

  1. We create a Future called futureInt that resolves to 42 after a delay of 2 seconds.
  2. We register a function using whenComplete to print a completion message regardless of the outcome.

Dart Program

void main() {
  Future<int> futureInt = Future.delayed(Duration(seconds: 2), () => 42);
  futureInt.whenComplete(() {
    print('Future completed.');
  });
}

Output

Future completed.

2 Handling completion with an error

In this example,

  1. We create a Future called futureString that throws an exception after a delay of 3 seconds.
  2. We register a function using whenComplete to print a completion message regardless of the outcome.

Dart Program

void main() {
  Future<String> futureString = Future.delayed(Duration(seconds: 3), () => throw Exception('Error!'));
  futureString.whenComplete(() {
    print('Future completed.');
  });
}

Output

Future completed.

3 Handling completion with a list value

In this example,

  1. We create a Future> called futureList that resolves to [1, 2, 3] after a delay of 1 second.
  2. We register a function using whenComplete to print a completion message regardless of the outcome.

Dart Program

void main() {
  Future<List<int>> futureList = Future.delayed(Duration(seconds: 1), () => [1, 2, 3]);
  futureList.whenComplete(() {
    print('Future completed.');
  });
}

Output

Future completed.

Summary

In this Dart tutorial, we learned about whenComplete() method of Future: the syntax and few working examples with output and detailed explanation for each example.