Sub topic 3
Futures: values that arrive later
Assume you know basic Dart functions, variables, types, generics, callbacks, and how to run a program with dart run. This chapter focuses on the object that represents an asynchronous result: Future<T>.
What a Future represents
A Future<T> is a promise that an operation will eventually produce a value of type T, or an error. The operation might read a file, call a web service, or wait for a timer.
A Future does not contain the final value immediately. It has one of these states:
| State | Meaning |
|---|---|
| Pending | The operation has not finished |
| Completed with a value | The operation succeeded |
| Completed with an error | The operation failed |
A Future completes only once. After completion, its result does not change.
The type inside the angle brackets describes the eventual value:
Future<String>eventually produces aString.Future<int>eventually produces anint.Future<void>completes without producing a useful value.
Waiting for a Future
The await keyword pauses the current asynchronous function until the Future completes. It does not block the whole Dart program. While the operation is pending, Dart can process other events.
Future<String> fetchGreeting() {
return Future.delayed(
const Duration(seconds: 1),
() => 'Hello',
);
}
Future<void> main() async {
print('before');
final greeting = await fetchGreeting();
print(greeting);
print('after');
}The output is:
before
Hello
afterfetchGreeting() starts an operation that completes after about one second. The variable greeting receives a String only after await finishes.
A function that uses await must normally have the async modifier. An async function returns a Future automatically. Therefore, even though main does not explicitly return a value, its type is effectively Future<void>.
The Future lifecycle
This diagram shows the one-way lifecycle of a Future.
You can create already-completed Futures as well as Futures that complete later.
Future<String> immediateValue() {
return Future.value('ready');
}
Future<int> delayedValue() {
return Future.delayed(
const Duration(milliseconds: 300),
() => 42,
);
}
Future<String> failedValue() {
return Future.error(StateError('No value available'));
}
Future<void> main() async {
print(await immediateValue());
print(await delayedValue());
try {
print(await failedValue());
} catch (error) {
print('Failure: $error');
}
}Future.value creates a successful Future immediately. Future.delayed completes later. Future.error creates a Future that completes with an error.
A Future is not its value
This common mistake treats a Future as though it were the value it will produce:
Future<int> loadCount() async => 7;
void wrong() {
// final count: int = loadCount(); // Type error
}loadCount() returns Future<int>, not int. Use await inside an asynchronous function:
Future<void> right() async {
final count = await loadCount();
print(count);
}You can also pass the Future to code that expects a Future. Do not add await merely because a function is asynchronous. Add it when you need the completed value, need to catch its error at that point, or need to control the order of later statements.
Exercise
What does this program print, and why does message have type String rather than Future<String>?
Show answer
It prints done after the delayed operation completes. await waits for the Future<String> and extracts its eventual String value before assigning it to message.