Async and Practical
Future Chain
.then().then()
.then(fn) runs fn once the prior future completes and produces the next future in the chain. Stacking .then calls gives a step-by-step pipeline; only the final future needs to be awaited. Because the chain starts from Future.value(...), no timers or external events are involved.
Program
Play the program to chain doubleIt and label onto a completed future.
future_chain.dart
Replay: real traced execution (multi-file project)
int doubleIt(int n) => n * 2;
String label(int n) => 'score=$n';
Future<void> main() async {
var chain = Future.value(5).then(doubleIt).then(label);
var result = await chain;
print(result);
}
chain ← Future.value(5) -> .then chain
4Future<void> main() async {5 var chain = Future.value(5).then(doubleIt).then(label);6 var result = await chain;values this stepFuture.value(5) -> .then chainchainreturn ← 10
1int doubleIt(int n) => n * 2;2String label(int n) => 'score=$n';values this step10return5nreturn ← score=10
1int doubleIt(int n) => n * 2;2String label(int n) => 'score=$n';values this stepscore=10return10nchain ← Future<String> -> score=10
4Future<void> main() async {5 var chain = Future.value(5).then(doubleIt).then(label);6 var result = await chain;values this stepFuture<String> -> score=10chainresult ← score=10
5var chain = Future.value(5).then(doubleIt).then(label);6var result = await chain;7print(result);values this stepscore=10result<future>chainprint(result);
6 var result = await chain;7 print(result);8}outputscore=10values this stepscore=10result
Future.value
`Future.value(5)` is already complete, so the chain has a value to push through right away.
.then
`.then(fn)` schedules `fn` on the prior future and yields a new future carrying `fn`'s return value.
await once
Only the final chained future needs `await`; intermediate `.then` callbacks already pass the value along.