Sub topic 3
Futures: values that arrive later
This chapter assumes you can read basic Dart (functions, variables, types), understand generics such as List<int>, can run a file with dart run, and know what a callback is. Earlier chapters covered the event loop. This one covers the object at the center of asynchronous Dart: the Future.
What a Future is
A Future<T> is an object that stands for a value of type T that is not available yet. It is also a promise that the value will arrive later, or that an error will arrive instead. Reading a file, calling a server, and waiting on a timer all return a Future, because the result depends on something outside your code.
A Future is a handle, not the value. This difference causes many beginner mistakes:
Future<int> slowDouble(int n) =>
Future.delayed(const Duration(milliseconds: 200), () => n * 2);
Future<void> main() async {
final pending = slowDouble(21);
print(pending); // Prints something like: Instance of '_Future<int>'
final value = await pending;
print(value); // 42
}The variable pending has type Future<int>, so you cannot add it to an int or call .isEven on it. You must wait for it first. Here await does that and gives you the int. The await keyword gets its own chapter. For now, read it as "pause this function until the Future finishes, then give me its result."
The states of a Future
A Future is always in one of two broad situations: it has not finished, or it has finished. A finished Future ends in exactly one of two ways.
| State | Meaning | What you receive |
|---|---|---|
| Uncompleted | The work is still running | Nothing yet |
| Completed with a value | The work succeeded | A value of type `T` |
| Completed with an error | The work failed | An exception and a stack trace |
A Future moves from uncompleted to one completed state, once. It never changes again. It cannot go back to uncompleted, and it cannot switch from a value to an error. Because the result is fixed, you can safely hand the same Future to many readers.
Dart's documentation sometimes says a Future is "completed" without saying how. Completing with an error still counts as completing. That is why code that handles only the success path can leave the failure path unhandled.
Completing with an error
An error is a normal outcome for a Future. If the work throws, the Future finishes in the error state. When you await it, the error is thrown again at that point, so an ordinary try/catch can handle it:
Future<int> failing() => Future.error(StateError('boom'));
Future<void> main() async {
final f = failing();
try {
await f;
print('not reached');
} on StateError catch (e) {
print('caught: ${e.message}');
}
}The output is caught: boom. The full treatment of error handling comes in a later chapter. Here the point is that the error travels inside the Future until someone reads it.
Reading a Future more than once
Because a completed Future never changes, you can read it as many times as you like. Each reader gets the same result:
Future<void> main() async {
final f = Future.delayed(const Duration(milliseconds: 100), () => 'ready');
print(await f); // waits about 100 ms, then prints: ready
print(await f); // already complete, prints: ready
}The work behind the Future runs once, however many listeners there are. This is a key difference from a function. Calling slowDouble(21) twice starts two separate pieces of work and creates two Futures. Awaiting one Future twice starts nothing new.
Callbacks never run immediately
Even when a Future is already complete, code that reacts to it does not run right away. Dart schedules the reaction to run later, on the microtask queue, after the current synchronous code finishes.
void main() {
print('1 before');
Future.value(10).then((v) => print('3 callback got $v'));
print('2 after');
}The output is 1 before, 2 after, 3 callback got 10. The Future is complete the moment it is created, but the callback still waits. This rule gives you a guarantee: code after a call that returns a Future always runs before that Future's reaction. You never see a half-finished state in the middle of your own function.
The type parameter
The T in Future<T> is the type of the value you eventually receive.
Future<int>completes with anint.Future<String?>completes with aStringornull.Future<List<User>>completes with a list.Future<void>completes with no useful value.
Future<void> is common for actions such as saving a file. You still await it, because the wait tells you the work is done, and any error still surfaces:
Future<void> saveSettings() async {
await Future<void>.delayed(const Duration(milliseconds: 50));
print('settings saved');
}
Future<void> main() async {
await saveSettings();
print('safe to continue');
}If you forget the await, 'safe to continue' prints before 'settings saved'. A later chapter covers this mistake in detail.
Dart does not nest Futures. If a Future would complete with another Future, Dart flattens them, so Future.value(Future.value(1)) has type Future<int>, not Future<Future<int>>. You do not have to unwrap results by hand.
Why there is no isCompleted check
Beginners often look for a property such as future.isCompleted or future.value. Dart has neither, on purpose. If you could check a Future and read its value now, you would be tempted to poll it in a loop. A polling loop blocks the single thread, so the Future's own work never gets a chance to run. The design forces you to hand Dart a reaction and let the event loop call it when the result is ready.
If you need to know whether something is done, keep that fact in your own state, or restructure the code to await the Future at the right place.
Unhandled errors
A Future that completes with an error and has no listener is dangerous. Nobody is positioned to read the error, so Dart reports it as an uncaught error:
void main() {
Future<int>.error(Exception('nobody is listening'));
print('main finished');
}This prints main finished. Then, when the event loop reaches the failed Future, the program reports the uncaught exception and exits with a non-zero status. The error was not lost silently, but it was not handled either.
FutureOr: a value or a Future
In library code you will sometimes see FutureOr<T>. It means "either a T or a Future<T>." A function can accept it when it does not care whether the result is ready now or later, and await works on both:
import 'dart:async';
FutureOr<int> maybeSlow(bool fast) {
if (fast) return 1;
return Future.delayed(const Duration(milliseconds: 100), () => 2);
}
Future<void> main() async {
print(await maybeSlow(true)); // 1
print(await maybeSlow(false)); // 2
}Awaiting a plain value is allowed. It just takes one trip through the microtask queue, so even await 1 lets other queued work run first.
Common errors at this stage
- Treating a
Future<T>as if it were aT. The analyzer usually catches this as a type error, but string interpolation does not.'Count: $future'compiles and prints the object description. - Expecting a Future to run its work again each time you read it. It runs once.
- Writing code that depends on a callback running before the next line. It never does.
- Creating a Future that can fail and not listening to it.
Summary
- A
Future<T>is a handle to a value of typeTthat arrives later. - It starts uncompleted and completes exactly once, with a value or with an error.
- A completed Future never changes, so many readers can get the same result.
- Reactions to a Future always run later, after the current synchronous code.
- Dart offers no way to peek at a Future's value. You give it a reaction instead.
- Always listen to Futures that can fail.
Exercise
What does this program print, and in what order? Explain why the callback line does not come first even though the Future is already complete. void main() { print('A'); Future.value(1).then((v) => print('B $v')); print('C'); }
Show answer
It prints A, then C, then B 1. Future.value(1) is already completed, but Dart schedules the then callback on the microtask queue instead of running it at once. The microtask runs only after the synchronous code in main (both prints) has finished.
Exercise
A teammate writes final f = fetchName(); print(f.length); where fetchName returns Future<String>. Why does this fail, and how do you fix it inside an async function?
Show answer
A Future<String> is a handle to a string that has not arrived yet, so it has no length property. Await it first: final name = await fetchName(); print(name.length);. The enclosing function must be marked async, and its return type becomes a Future.
Exercise
Two lines run print(await f); on the same Future f created with Future.delayed(const Duration(seconds: 1), () => 'x'). About how long does the second await wait, and does the delayed callback run again?
Show answer
The second await returns almost immediately, because f is already completed. The delayed callback does not run again. A Future runs its work once, and every reader receives the same stored result.