How is whenCompleted() different from then() in Future?

In Dart, both whenCompleted() and then() are methods used with Future objects to handle the result of a computation that might complete asynchronously. However, there are some key differences in how they behave and what they return:

  1. then(): The then() method is used to register callbacks that will be invoked when the Future completes, whether it completes with a value or an error. It takes two optional callback arguments: one for handling the value when the Future completes successfully, and another for handling any errors that might occur during the computation.

Syntax:

future.then((value) {
  // Handle the successful completion and value.
}, onError: (error) {
  // Handle any errors that occurred during the computation.
});
  • If the Future completes successfully, the then() method invokes the first callback with the computed value.
  • If the Future completes with an error, the then() method invokes the onError callback with the error object.

Example:

Future<int> fetchData() async {
  await Future.delayed(Duration(seconds: 2));
  return 42;
}

void main() {
  fetchData().then((value) {
    print('Data: $value'); // Output: Data: 42
  }, onError: (error) {
    print('Error: $error');
  });
}
  1. whenCompleted(): The whenCompleted() method is used to register a callback that will be invoked when the Future completes, regardless of whether it completed successfully or with an error. It does not handle the value or error; it only notifies you when the Future is completed.

Syntax:

future.whenComplete(() {
  // This callback is called when the Future completes, regardless of success or error.
});
  • The whenCompleted() method does not provide any information about the computed value or any errors that might have occurred during the computation.
  • It is suitable for situations where you need to perform cleanup or tasks that should happen regardless of the outcome of the Future.

Example:

Future<int> fetchData() async {
  await Future.delayed(Duration(seconds: 2));
  return 42;
}

void main() {
  fetchData().whenComplete(() {
    print('Fetch operation completed.');
  });
}

In this example, the whenCompleted() method is used to print a message when the fetch operation is completed, regardless of whether it succeeded or failed.

In summary, the main difference between then() and whenCompleted() in Future is that then() allows you to handle the successful result and errors, while whenCompleted() only allows you to register a callback to be executed when the Future completes, without providing access to the computed value or error. Use then() when you need to handle the result and errors, and use whenCompleted() when you need to perform actions that should occur regardless of the outcome of the Future.

error: Content is protected !!