Async and Practical
async/await
Pause and Resume
async marks a function that returns a Future; await pauses the surrounding async function until the future is ready, then resumes with the value. Future.value(x) produces an already-completed future, so the example is deterministic and free of timing.
Program
Play the program to await two futures in sequence and watch each resume bind its result.
async_await.dart
Replay: real traced execution (multi-file project)
Future<int> getCount() {
return Future.value(7);
}
Future<int> twice(int n) async {
return n * 2;
}
Future<void> main() async {
var a = await getCount();
var b = await twice(a);
print('$a $b');
}
awaiting ← getCount()
9Future<void> main() async {10 var a = await getCount();11 var b = await twice(a);values this stepgetCount()awaitingreturn value ← Future.value(7)
1Future<int> getCount() {2 return Future.value(7);3}values this stepFuture.value(7)return valueresumed ← a = 7
9Future<void> main() async {10 var a = await getCount();11 var b = await twice(a);values this stepa = 7resumedawaiting ← twice(7)
10var a = await getCount();11var b = await twice(a);12print('$a $b');values this steptwice(7)awaiting7areturn value ← 14
5Future<int> twice(int n) async {6 return n * 2;7}values this step14return value7nresumed ← b = 14
10var a = await getCount();11var b = await twice(a);12print('$a $b');values this stepb = 14resumedprint('$a $b');
11 var b = await twice(a);12 print('$a $b');13}output7 14values this step7a14b
async function
An `async` function (like `twice`) returns a `Future<T>` automatically; `return n * 2` becomes `Future.value(n * 2)`.
Future.value
`Future.value(7)` is an already-completed future, so the example needs no timers, files, network, or external events.
pause and resume
Each `await fn()` suspends `main` until the future is ready, then resumes with the value bound into a local.