Difference between .then() and .whenCompleted() methods when working with Futures?

.whenComplete will fire a function either when the Future completes with an error or not, instead .then will fire a function after the Future completes without an error.

Quote from the .whenComplete API DOC

This is the asynchronous equivalent of a "finally" block.


.whenComplete = The function inside .whenComplete is called when this future completes, whether it does so with a value or with an error.

.then = Returns a new Future which is completed with the result of the call to onValue (if this future completes with a value) or to onError (if this future completes with an error)

Read detail on API DOC

whenComplete then


Even if there is an error, then can still be invoked, provided you have specified catchError.

someFuture.catchError(
  (onError) {
    print("called when there is an error catches error");
  },
).then((value) {
  print("called with value = null");
}).whenComplete(() {
  print("called when future completes");
});

So, if there is an error, all the above callbacks gets called.

Tags:

Dart