CodeBlanks Logo Icon CodeBlanks

then

Learn Future chaining with .then.

then

You specify what happens when a Future completes with .then. .then takes a callback; when the Future completes with a value the callback runs and receives the value. Future.value(5).then((v) => print(v));.

Multiple .then calls can be chained; each feeds the next. Future.value(5).then((v) => v * 2).then((v) => print(v)); prints 10. This is the idiomatic way to transform a value step by step. Even though async/await is more readable, .then is still common; especially for short chains.

Chaining then

When multiple .then calls are written side by side they form a chain. The first .then receives the Future's value; its return value is passed to the next .then. This is ideal for sequential transforms.

Example: Future.value(3).then((v) => v + 1).then((v) => v * 10).then((v) => print(v));. The output is 40. Each .then returns a new Future; so the chain is a sequence of Futures. If a step throws, the rest of the chain is skipped and control goes to .catchError. We will see error handling in the next lesson.

Practice Your turn: then chain

Start with Future.value(5). Double the value with .then((v) => v * 2), then print it with .then((v) => print(v)). You build a two-step then chain.

Starter code

main.dart
void main() {
  // Start with a value Future
  // .then to double
  // .then to print
}

Sample solution

main.dart
void main() {
  Future.value(5).then((v) => v * 2).then((v) => print(v));
}

Expected output

10

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match then

Term Meaning
.then runs on completion
(v) => v * 2 transforms the value
chaining step by step
callback the function passed

2 The then callback

Question
Future.value(5).____((v) => print(v));
Answer
Future.value(5).then((v) => print(v));

Explanation: then provides the completion callback.

3 What does Future.value(3).then((v) => v + 1).then((v) => print(v)) print?

main.dart
Future.value(3)
  .then((v) => v + 1)
  .then((v) => print(v));
  • 1 Correct answer
  • 3
  • 4
  • 7

Explanation: The first then turns 3 into 4, the second prints 4; result is 4.

All lessons in Beginner