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?
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.
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 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.
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.
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With