Dart Futures
Many operations take time: reading a file, querying a database, calling a web API. Blocking the program while waiting would freeze a UI or stall a server. Dart handles this with asynchronous programming, and the basic building block is Future<T> — an object representing a value of type T that will be available later.
The event loop in one minute
A Dart program runs on a single thread (per isolate) with an event loop:
- Run
mainto completion (synchronous code). - Run everything in the microtask queue (tiny follow-up tasks, e.g. completed futures' callbacks).
- Take the next event (timer, I/O result, message) from the event queue, run it, then go back to step 2.
Because there's only one thread, synchronous code always runs uninterrupted. Asynchronous results are delivered between pieces of synchronous work.
void main() {
print('1. main starts');
Future(() => print('4. event-queue task'));
Future.microtask(() => print('3. microtask'));
Future.delayed(Duration(milliseconds: 10), () => print('5. timer after 10 ms'));
print('2. main ends');
}1. main starts
2. main ends
3. microtask
4. event-queue task
5. timer after 10 ms
The callbacks were registered in the middle of main, but they run only after main finishes.
Future states
A future is either uncompleted or completed — with a value or with an error.
┌──> completed with value (then)
uncompleted ────┤
└──> completed with error (catchError)Consuming a future with then
then registers a callback for the value and returns a new future, so calls can be chained. catchError handles failures, and whenComplete runs either way (like finally):
Future<int> fetchStock(String item) =>
Future.delayed(Duration(milliseconds: 20), () {
if (item == 'unicorn') throw StateError('unknown item: $item');
return item.length * 10;
});
void main() {
print('requesting...');
fetchStock('lamp')
.then((qty) => qty * 2)
.then((doubled) => print('lamp x2: $doubled'))
.whenComplete(() => print('lamp request done'));
fetchStock('unicorn')
.then((qty) => print('never printed: $qty'))
.catchError((e) => print('failed: ${(e as StateError).message}'));
}requesting...
lamp x2: 80
lamp request done
failed: unknown item: unicorn
Note: Chains of
thenget hard to read quickly. Most modern Dart usesasync/awaitinstead — the next lesson. Understandingthenstill helps, becauseawaitis built on exactly this mechanism.
Creating futures
| Constructor | Result |
|---|---|
Future.value(x) |
Already completed with x |
Future.error(e) |
Already completed with an error |
Future.delayed(d, [fn]) |
Completes after duration d with fn() |
Future(fn) |
Runs fn in a later event-queue task |
Future.microtask(fn) |
Runs fn as a microtask |
Completer<T>() |
Complete a future manually (bridges callback APIs) |
import 'dart:async';
// Wrapping a callback-style API with a Completer
void legacyLoad(void Function(String data) onDone) {
Timer(Duration(milliseconds: 5), () => onDone('payload'));
}
Future<String> load() {
final completer = Completer<String>();
legacyLoad((data) => completer.complete(data));
return completer.future;
}
void main() {
Future.value(42).then((v) => print('value: $v'));
load().then((d) => print('loaded: $d'));
}value: 42
loaded: payload
Running futures together
Future.wait runs several futures concurrently and completes when all are done, with a list of results in the same order. Future.any completes with the first one to finish.
Future<String> fetch(String name, int ms) =>
Future.delayed(Duration(milliseconds: ms), () => '$name($ms ms)');
void main() {
final watch = Stopwatch()..start();
Future.wait([fetch('users', 60), fetch('orders', 30), fetch('stats', 45)]).then((results) {
print(results);
// all three ran at the same time, so this is ~60 ms, not 135 ms
print('took < 120 ms: ${watch.elapsedMilliseconds < 120}');
});
Future.any([fetch('mirror-a', 50), fetch('mirror-b', 20)]).then((first) {
print('fastest: $first');
});
}fastest: mirror-b(20 ms)
[users(60 ms), orders(30 ms), stats(45 ms)]
took < 120 ms: true
Dart 3 also adds a records-based form: final (a, b) = await (fetchA(), fetchB()).wait; — typed results without a list.
Common pitfalls
- Forgetting the future. Calling an async function without awaiting or handling it means errors may go unnoticed. The
unawaited_futureslint flags this. - Expecting order between independent futures. Two unrelated futures complete in whatever order their work finishes.
- Blocking work. A future doesn't make CPU-heavy code run in parallel — it still runs on the same thread. For heavy computation use an isolate.
Test yourself
When does a callback registered with Future.microtask run relative to a Future(() => …) task?
- After it
- Before it — microtasks run before the next event
- At the same time
- Never
What does Future.wait([a, b, c]) complete with?
- The first result
- A list of all results in the original order
- The last result to finish
- void
Does wrapping CPU-heavy code in a Future make it run on another thread?
- Yes
- No — it still runs on the same isolate's thread
- Only on the web
- Only with Future.delayed