Sub topic 14
Asynchronous code with Future, async, and await
This chapter assumes you can write Dart functions, handle exceptions with try/catch, and use closures. You should also know what a callback is. By the end you will know how Dart schedules asynchronous work, how to write and combine Future values, and which mistakes cause silent bugs.
Why asynchronous code exists
Waiting on a network call, a file, or a timer should not freeze the program. In Flutter, a frozen program means a frozen screen. Dart handles this with futures rather than blocking.
A Future<T> is an object that represents a value of type T that is not available yet. It is in one of three states:
A future completes exactly once. After that, its result never changes.
The event loop in one page
Each Dart isolate (Dart's unit of execution, with its own memory) runs on a single thread. Async code is therefore concurrent but not parallel. Two queues feed that thread:
- The microtask queue holds short internal jobs. It is always drained completely first.
- The event queue holds timers, I/O completions, and
Future(...)bodies.
The thread runs your synchronous code to the end. Then it runs all microtasks. Then it takes one event, and repeats.
import 'dart:async';
void main() {
print('1 start');
Future(() => print('4 event queue'));
scheduleMicrotask(() => print('3 microtask'));
print('2 end of main body');
}The output is numbered in the order it prints. Synchronous code always finishes first, then microtasks, then events. Practical consequence: a long loop with no await blocks everything, including UI frames. Marking a function async does not move work to another thread.
async and await
An async function always returns a Future. Inside it, await pauses that function until a future completes and gives you the value. Other code keeps running while it waits.
Future<String> fetchName() async {
await Future.delayed(const Duration(milliseconds: 100));
throw StateError('network down');
}
Future<void> main() async {
try {
print(await fetchName());
} on StateError catch (e) {
print('Failed: ${e.message}');
} finally {
print('done');
}
}Points to notice:
awaitcan appear only inside a function markedasync(orasync*).- A failed future rethrows its error at the
await. That is why ordinarytry/on/catch/finallyworks. return 5;insideFuture<int> f() asyncwraps the value in a future for you. You can also return aFuture<int>directly.- A function that does async work but returns nothing should be
Future<void>, notvoid. Avoidreturn type gives the caller nothing to await.
Sequential versus concurrent
A future starts running as soon as you create it, not when you await it. This lets you control how much work overlaps.
Future<int> slow(int n) async {
await Future.delayed(const Duration(milliseconds: 200));
return n * 10;
}
Future<void> main() async {
final watch = Stopwatch()..start();
final a = await slow(1);
final b = await slow(2);
print('sequential: $a $b in ${watch.elapsedMilliseconds} ms');
watch.reset();
final results = await Future.wait([slow(1), slow(2)]);
print('concurrent: $results in ${watch.elapsedMilliseconds} ms');
}The sequential version takes about 400 ms because the second call does not start until the first finishes. The Future.wait version takes about 200 ms because both calls are already running when the wait begins.
Future.wait takes a list and returns a list in the same order as the input, not the completion order. All futures in the list must share one type. For different types, Dart 3 offers a .wait getter on records of futures. It keeps each type:
Future<int> slow(int n) async {
await Future.delayed(const Duration(milliseconds: 50));
return n * 10;
}
Future<String> label() async => 'total';
Future<void> main() async {
final (number, text) = await (slow(4), label()).wait;
print('$text: $number');
}If any future in a Future.wait fails, the combined future fails with that error. By default the other futures still run to completion, but their results are discarded.
Callbacks: then, catchError, and whenComplete
Before await, code chained callbacks. You will still see this style in older code and libraries:
Future<void> main() {
return Future.delayed(const Duration(milliseconds: 50), () => 21)
.then((value) => value * 2)
.then((value) => print('result: $value'))
.catchError((Object e) => print('error: $e'))
.whenComplete(() => print('finished'));
}Each then returns a new future, so the chain reads top to bottom. Here the function returns the final future, which keeps the program alive until the chain finishes. Prefer async/await in new code. It reads like synchronous code, and try/catch covers the whole block. The chained form is still useful for one-line transformations.
Timeouts and creating futures by hand
Future.timeout fails a future that takes too long. The error is a TimeoutException from dart:async:
import 'dart:async';
Future<void> main() async {
try {
await Future.delayed(const Duration(seconds: 2))
.timeout(const Duration(milliseconds: 100));
} on TimeoutException {
print('timed out');
}
}Note that a timeout stops waiting. It does not cancel the underlying work. Dart futures cannot be cancelled.
Other constructors you will use:
| Expression | What it gives you |
|---|---|
| `Future.value(3)` | A future already completed with a value |
| `Future.error(StateError('x'))` | A future already completed with an error |
| `Future.delayed(d, fn)` | A future that runs `fn` after duration `d` |
| `Future(() => compute())` | A future that runs the function on the event queue |
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Forgetting `await` | You hold a `Future`, not the value. The code compiles when the type allows it, such as with `print`. | Add `await`, or enable the `unawaited_futures` lint |
| Using `list.forEach((x) async { await ... })` | `forEach` ignores the returned futures, so the loop finishes immediately | Use `for (final x in list) { await ... }` or `Future.wait` |
| Awaiting in a loop when work is independent | Total time is the sum of all calls | Start all futures, then `Future.wait` |
| Errors in a future nobody awaits | An uncaught async error can crash the program | Await it, or attach `catchError` |
| Heavy computation inside an `async` function | The UI still freezes | Use `Isolate.run` for CPU-heavy work |
Where this leads
Futures deliver one value. Many sources deliver several values over time, such as keystrokes or sensor readings. Dart models those as streams, covered in a later chapter. The same async and await keywords carry over, with async* and await for.
Exercise
Predict the output order of this program, and say how long it takes: Future<void> main() async { final a = Future.delayed(const Duration(milliseconds: 300), () => 'A'); final b = Future.delayed(const Duration(milliseconds: 100), () => 'B'); print(await a); print(await b); }
Show answer
It prints A, then B, in about 300 ms. Both futures start when they are created, so they run concurrently. B finishes first, but the code awaits a first, so A prints first. When await b runs, B is already complete and returns at once. Total time is the longest delay (300 ms), not the sum (400 ms).
Exercise
A teammate writes ids.forEach((id) async { await save(id); }); print('all saved'); and sees "all saved" before the saves finish. Explain why and give a corrected version that saves one after another, and one that saves all at once.
Show answer
forEach calls the callback and ignores the future it returns, so it does not wait. The function is not awaited, and 'all saved' prints right after the loop starts the callbacks. Sequential fix: for (final id in ids) { await save(id); } print('all saved');. Concurrent fix: await Future.wait(ids.map(save)); print('all saved');. Both must be inside an async function.