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?