Dart Future then()
Syntax & Examples
Future.then() method
The `then` method in Dart registers callbacks to be called when a future completes.
Syntax of Future.then()
The syntax of Future.then() method is:
Future<R> then<R>(FutureOr<R> onValue(T value), { Function onError })
This then() method of Future register callbacks to be called when this future completes.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
onValue | required | A callback function to be called when the future completes successfully, with the value of the future as an argument. |
onError | optional | A callback function to be called if the future completes with an error. |
Return Type
Future.then() returns value of type Future<R>
.
✐ Examples
1 Handling successful completion
In this example,
- We create a Future
called futureInt
that resolves to 42 after a delay of 2 seconds. - We register a callback using
then
to print the value when the future completes successfully.
Dart Program
void main() {
Future<int> futureInt = Future.delayed(Duration(seconds: 2), () => 42);
futureInt.then((value) {
print('Future completed with value: $value');
});
}
Output
Future completed with value: 42
2 Handling completion with an error
In this example,
- We create a Future
called futureString
that throws an exception after a delay of 3 seconds. - We register callbacks using
then
to print the value on success and the error on failure.
Dart Program
void main() {
Future<String> futureString = Future.delayed(Duration(seconds: 3), () => throw Exception('Error!'));
futureString.then((value) {
print('Future completed with value: $value');
}, onError: (error) {
print('Future completed with error: $error');
});
}
Output
Future completed with error: Exception: Error!
3 Handling completion with a list value
In this example,
- We create a Future
- > called
futureList
that resolves to [1, 2, 3] after a delay of 1 second. - We register a callback using
then
to print the list when the future completes successfully.
Dart Program
void main() {
Future<List<int>> futureList = Future.delayed(Duration(seconds: 1), () => [1, 2, 3]);
futureList.then((value) {
print('Future completed with value: $value');
});
}
Output
Future completed with value: [1, 2, 3]
Summary
In this Dart tutorial, we learned about then() method of Future: the syntax and few working examples with output and detailed explanation for each example.