Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dart

I'm exploring Futures in Dart, and I'm confused about these two methods that Future offers, .then() and .whenCompleted(). What's the main difference between them?

Lets say I want to read a .txt using .readAsString(), I would do it like this:

void main(){   File file = new File('text.txt');   Future content = file.readAsString();   content.then((data) {     print(content);   });   } 

So .then() is like a callback that fires a function once the Future is completed.

But I see there is also .whenComplete() that can also fire a function once Future completes. Something like this :

void main(){   File file = new File('text.txt');   Future content = file.readAsString();   content.whenComplete(() {     print("Completed");   }); } 

The difference I see here is that .then() has access to data that was returned! What is .whenCompleted() used for? When should we choose one over the other?

like image 740
Matija Avatar asked Mar 27 '19 15:03

Matija


People also ask

How do you use Ifcomplete in Flutter?

whenComplete(() => print('do something here')); // Prints "do something here" after waitTask() completed. print(value); // Prints "done" } Future<String> waitTask() { Future. delayed(const Duration(seconds: 5)); return Future. value('done'); } // Outputs: 'do some work here' after waitTask is completed.

What is Future method importance in Dart?

A Future is used to represent a potential value, or error, that will be available at some time in the future. Receivers of a Future can register callbacks that handle the value or error once it is available.

What is then () in Flutter?

What is Async/Await/then In Dart/Flutter? await is to interrupt the process flow until the async method completes. then however does not interrupt the process flow. This means that the next instructions will be executed. But it allows you to execute the code when the asynchronous method completes.

How do you handle Future error in Flutter?

That error is handled by catchError() . If myFunc() 's Future completes with an error, then() 's Future completes with that error. The error is also handled by catchError() . Regardless of whether the error originated within myFunc() or within then() , catchError() successfully handles it.


1 Answers

.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.

like image 82
Mattia Avatar answered Sep 28 '22 07:09

Mattia