Sub topic 4
Creating Futures
This chapter assumes you can read basic Dart, understand generics such as Future<int>, and run a program with dart run. It also assumes you know what a Future is and how the event loop and microtask queue order work. Here you will learn the ways to create a Future yourself, when each one fits, and what each one does with timing and errors.
Why creation matters
Most Futures come from library calls such as file reads or HTTP requests. You also create Futures yourself in several situations:
- You write a function that must return a
Futurebut can sometimes answer immediately, for example from a cache. - You write tests that need a Future that succeeds, fails, or takes a fixed time.
- You want to push a piece of work to a later turn of the event loop.
- You want to wrap code that does not use Futures at all. The
Completerchapter covers that case.
The core constructors are Future(), Future.value, Future.error, and Future.delayed. Dart also has Future.microtask and Future.sync. Every one of them returns a Future<T>. They differ in when the work runs and how failure is reported.
| Constructor | Runs the work | Completes with |
|---|---|---|
| `Future(computation)` | Later, on the event queue | The return value, or an error if it throws |
| `Future.microtask(computation)` | Later, on the microtask queue | The return value, or an error if it throws |
| `Future.sync(computation)` | Immediately | The return value, or an error if it throws |
| `Future.value(value)` | No work to run | The given value |
| `Future.error(error)` | No work to run | The given error |
| `Future.delayed(duration, computation)` | After the duration, on the event queue | The return value, or an error if it throws |
Future.value and Future.error
Future.value creates a Future that is already complete with a value. Future.error creates one that is already complete with an error. They are the simplest way to satisfy a function signature that promises a Future.
Future<int> cachedCount(Map<String, int> cache, String key) {
final hit = cache[key];
if (hit != null) {
return Future.value(hit);
}
return Future<int>.error(StateError('No entry for $key'));
}
Future<void> main() async {
final cache = {'apples': 3};
print(await cachedCount(cache, 'apples'));
try {
await cachedCount(cache, 'pears');
} on StateError catch (e) {
print('caught: ${e.message}');
}
}Two details matter here.
First, "already complete" does not mean callbacks run immediately. Even when a Future is complete, code attached with then or resumed after await is scheduled on the microtask queue. A caller can therefore never observe the callback running before the line that registered it has finished. This keeps behavior consistent whether the value was cached or slow.
Second, Future.value flattens. If you pass it another Future, the result completes with that Future's outcome and does not wrap it in a second layer. Future<int>.value(Future.value(1)) is a Future<int>, not a Future<Future<int>>.
Errors need a listener
A Future that completes with an error and has no handler attached becomes an uncaught asynchronous error. The runtime reports it, and in a command-line program that usually ends the program. Handlers must be attached in time. If you create Future.error(...) and store it, then attach a handler several event-loop turns later, the error may already have been reported as unhandled.
Future<void> main() async {
final failing = Future<int>.error(StateError('boom'));
try {
await failing;
} on StateError catch (e) {
print('caught: ${e.message}');
}
}In this example await attaches the handler in the same turn as the creation, so the error is delivered to the catch clause.
Future(): scheduling work on the event queue
The unnamed constructor takes a function and runs it later. The function is placed on the event queue. It does not run during the current synchronous code, and it does not run before any pending microtasks.
import 'dart:async';
void main() {
print('1 main start');
Future(() => print('5 Future()'));
Future.delayed(Duration.zero, () => print('6 delayed zero'));
Future.microtask(() => print('3 microtask'));
Future.value(0).then((_) => print('4 value then'));
print('2 main end');
}The output is numbered in the order it prints. Synchronous code finishes first. Then the microtask queue drains in the order tasks were added: the microtask entry and then the then callback on the completed value. Only after that does the event queue run Future() and the zero-duration Future.delayed, in the order they were scheduled.
If the function passed to Future() throws, the exception does not escape to the caller. It becomes an error result of the returned Future.
Future<void> main() async {
final f = Future<int>(() => throw const FormatException('bad data'));
print('created, nothing thrown yet');
try {
await f;
} on FormatException catch (e) {
print('caught: ${e.message}');
}
}If the function returns a Future, the outer Future waits for it and completes with its result. That flattening is the same as in Future.value.
Future.delayed
Future.delayed waits for a Duration and then runs an optional function. It is the standard way to simulate latency in examples and tests, and also a simple way to pause inside an async function.
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 program prints before, pauses about a second, then prints Hello and after. The delay is a minimum, not a guarantee. The callback runs when the event loop is free and the time has passed. A long-running synchronous function in the same isolate pushes it later.
You can omit the function when you only need to wait:
Future<void> main() async {
print('waiting');
await Future<void>.delayed(const Duration(milliseconds: 200));
print('200 ms later');
}Without a function, the Future completes with null. That is why the type must be Future<void> or a nullable type. Asking for a non-nullable type such as Future<int>.delayed(duration) without a function fails at runtime, because there is no value to complete with.
Future.microtask and Future.sync
Two less common constructors are worth knowing because they expose the queue rules directly.
Future.microtask is like Future(), but it schedules the function on the microtask queue. It runs before any event-queue work, including timers and I/O callbacks. Use it rarely. A task that keeps adding microtasks can starve the event queue, so the app stops responding to input.
Future.sync runs the function immediately, in the current synchronous turn, and wraps the outcome in a Future. If the function throws, you get an error Future and no exception reaches the caller. This is useful for functions that return a Future but do some synchronous validation first.
import 'dart:async';
Future<int> parsePositive(String text) {
return Future.sync(() {
final n = int.parse(text);
if (n <= 0) {
throw RangeError.value(n, 'text', 'Must be positive');
}
return n;
});
}
Future<void> main() async {
print('before call');
final f = parsePositive('-4');
print('after call, no exception yet');
try {
await f;
} on RangeError catch (e) {
print('caught: ${e.message}');
}
}Both prints before the try appear, because the failure is stored in the Future. An async function gives the same guarantee. Marking the function async is usually the simpler way to write this, and the next chapters use it. Future.sync is handy when the function is not async and you want the same behavior.
Choosing a constructor
Futures created by async functions
You rarely need these constructors inside code that is already async. An async function returns a Future automatically. A return completes it with a value, and a throw completes it with an error. The constructors in this chapter matter most in non-async functions that return a Future, in tests, and when adapting other code.
Common mistakes
- Expecting the function in
Future()to run now. It does not. Code after the constructor runs first. - Storing a failed Future and handling it later. The runtime may report the error as unhandled before you attach a handler. Attach handlers right away.
- Creating
Future<T>.delayedwith a non-nullableTand no function. There is no value to complete with, so it fails. - Using
Future.delayed(Duration.zero)as a fix for ordering bugs. It moves work to a later turn but hides the real dependency. - Forgetting the type argument on
Future.error. Without it you getFuture<dynamic>, so writeFuture<int>.error(...)when the signature expectsFuture<int>.
Exercise
What does the following program print, in order? Explain why. import 'dart:async'; void main() { print('a'); Future(() => print('d')); Future.value(1).then((_) => print('c')); Future.sync(() => print('b')); print('e'); }
Show answer
It prints a, b, e, c, d. 'a' prints first as ordinary synchronous code. Future.sync runs its function immediately, so 'b' prints next. 'e' follows because main still has to finish its synchronous code. Then the microtask queue drains, and the then callback on the already-complete Future.value prints 'c'. Last, the event queue runs the function passed to Future(), which prints 'd'.
Exercise
Write a function Future<int> half(int n) that is not marked async. It must return a Future that completes with n ~/ 2 when n is even and completes with an ArgumentError when n is odd, and it must never throw synchronously. Which constructors could you use?
Show answer
Future<int> half(int n) { return n.isEven ? Future.value(n ~/ 2) : Future<int>.error(ArgumentError.value(n, 'n', 'Must be even')); } Future.sync with a function that throws on odd input also works, because it turns the thrown exception into an error Future.