The `then` method in Dart registers callbacks to be called when a future completes.
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.
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. |
Future.then() returns value of type Future<R>
.
In this example,
futureInt
that resolves to 42 after a delay of 2 seconds.then
to print the value when the future completes successfully.void main() {
Future<int> futureInt = Future.delayed(Duration(seconds: 2), () => 42);
futureInt.then((value) {
print('Future completed with value: $value');
});
}
Future completed with value: 42
In this example,
futureString
that throws an exception after a delay of 3 seconds.then
to print the value on success and the error on failure.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');
});
}
Future completed with error: Exception: Error!
In this example,
futureList
that resolves to [1, 2, 3] after a delay of 1 second.then
to print the list when the future completes successfully.void main() {
Future<List<int>> futureList = Future.delayed(Duration(seconds: 1), () => [1, 2, 3]);
futureList.then((value) {
print('Future completed with value: $value');
});
}
Future completed with value: [1, 2, 3]
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.