Future chaining
- Dart course
- Intermediate
- Lesson 60/116
- 5 min
Learn Future chaining with .then and .catchError.
then and catchError
With .then and .catchError you catch the result or the error of a Future. .then runs when the Future completes successfully; .catchError when it throws.
Example: Future.value(10).then((v) => print(v)).catchError((e) => print(e));. Here .then receives the value 10 and prints it. If there were an error .catchError would run.
These methods are chainable; each .then feeds the next. They are an alternative to await; sometimes more convenient.
Chaining
.then and .catchError are used chained. Each .then returns a new Future; the next .then receives its result. This way the data flow works like a pipeline.
Example: Future.value(10).then((v) => v * 2).then((v) => print(v));. The first .then turns 10 into 20; the second .then prints 20. Output: 20.
If any step in the chain errors, the next .catchError catches it. This centralizes error handling.
Practice Print the result with then
void main() async is already written. Create Future.value(10). Add .then((v) => print('Result: $v')). Add .catchError((e) => print('Error: $e')). Wait for the whole chain with await.
Starter code
void main() async {
// produce 10 with a Future, print with .then, catch errors with .catchError
// await the whole chain
}Sample solution
void main() async {
await Future.value(10)
.then((v) => print('Result: $v'))
.catchError((e) => print('Error: $e'));
}Expected output
Result: 10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the then/catchError parts
| Term | Meaning |
|---|---|
.then((v) => ...) |
Success handler |
.catchError((e) => ...) |
Error handler |
v |
Result value |
e |
Error object |
2 When does catchError run?
Future.value(10)
.then((v) => print(v))
.catchError((e) => print(e));- When the Future completes successfully
- Never
- Always
- When the Future throws an error Correct answer
Explanation: catchError runs only when the Future throws an error.
3 The then call
Future.value(10)
____((v) => print('Result: $v'))
.catchError((e) => print('Error: $e'));
Future.value(10)
then((v) => print('Result: $v'))
.catchError((e) => print('Error: $e'));
Explanation: then is the success handler.