Sub topic 4
Creating Futures in Dart
Assume you know basic Dart functions, variables, types, generics, callbacks, and how to run a program with dart run. This chapter focuses on creating a Future, not on consuming one with await.
A Future<T> represents one result that will be available later. The type parameter T describes the successful result. For example, Future<String> eventually produces a String.
The states of a Future
A Future moves through these states:
- Uncompleted: the operation is still running.
- Completed with a value: the operation succeeded and produced a value of type
T. - Completed with an error: the operation failed and produced an error instead of a value.
A Future completes only once. It cannot later change from one successful value to another value.
Common ways to create a Future
Dart provides several constructors for common situations.
| Constructor | Result timing | Typical use |
|---|---|---|
| `Future(() => value)` | Later, through the event queue | Schedule a computation |
| `Future.value(value)` | Already successful | Adapt an existing value |
| `Future.delayed(duration, callback)` | After a delay | Timers, demos, retry delays |
| `Future.error(error)` | Already failed | Report a failure |
Scheduling a computation
Future with a callback schedules that callback to run later. The callback's return value becomes the Future's value.
Future<int> calculate() {
return Future(() {
print('calculation runs later');
return 6 * 7;
});
}
Future<void> main() async {
print('before');
final result = await calculate();
print('result: $result');
}The callback runs asynchronously, but this does not create a new isolate or a second CPU thread. The same Dart isolate still performs the calculation. A long CPU-heavy callback can therefore block other work.
Wrapping an existing value
Use Future.value when a function must return a Future even though its result is already known.
Future<String> cachedGreeting() {
return Future.value('Hello from the cache');
}
Future<void> main() async {
print(await cachedGreeting());
}This is useful when two implementations must have the same return type:
Future<String> loadGreeting(bool useCache) {
if (useCache) {
return Future.value('Cached greeting');
}
return Future.delayed(
const Duration(milliseconds: 200),
() => 'Greeting from storage',
);
}Delayed and failed Futures
Future.delayed waits for the specified duration before running its callback. The callback is optional. Without a callback, the Future completes with null, so provide a type such as Future<void> when appropriate.
Future.error creates a Future that completes with an error. The error must be handled by a listener, await inside try, or another error-handling method.
Future<String> fetchFromServer() {
return Future.delayed(
const Duration(milliseconds: 300),
() => 'Server response',
);
}
Future<String> rejectRequest() {
return Future.error(StateError('The request was rejected'));
}
Future<void> main() async {
print(await fetchFromServer());
try {
await rejectRequest();
} on StateError catch (error) {
print('Request failed: $error');
}
}A Future's error is not a return value. Code must handle it separately, or the program may report an unhandled asynchronous error.
Choosing a constructor
Use Future.value for an immediate known result, Future.delayed when time must pass before completion, and Future.error when you need to expose a failure through a Future. Use Future(() => ...) to schedule ordinary asynchronous work, while remembering that it still runs in the current isolate.
Exercise
Which constructor should you use for a function that returns a cached int but must have the type Future<int>?
Show answer
Use Future.value(cachedInt).