Sub topic 11
Bridging callbacks to Futures with Completer
This chapter assumes you know how async and await work, how a Future completes with a value or an error, and how try/catch handles awaited errors. It also assumes you can read a callback-style API, meaning a function that takes onSuccess and onError functions instead of returning a result. If any of that is unfamiliar, review the earlier chapters on Futures and error handling first.
Why Completer exists
Most Futures come from code you do not write yourself. Future.delayed, http.get, and File.readAsString already return one. Some APIs predate Futures, though. They report results through callbacks, timers, or event listeners. You cannot await a callback, so you need a way to turn "this function will call me later" into "this object will hold the answer later".
A Completer<T> does that. It owns a Future<T> and exposes the controls to finish it. You hand the future to callers. You keep the completer and finish it from inside your callback.
You can think of it as a Future split into two halves:
- The
futurehalf is read-only. Callersawaitit or chainthenon it. - The completer half is write-only. Only the code that holds the completer can call
completeorcompleteError.
The basic shape
The countdown below reports its result through a periodic Timer callback. The Future it returns completes when the last tick fires.
import 'dart:async';
Future<int> countdown(int from) {
final completer = Completer<int>();
var n = from;
Timer.periodic(const Duration(milliseconds: 100), (timer) {
n--;
if (n == 0) {
timer.cancel();
completer.complete(from);
}
});
return completer.future;
}
Future<void> main() async {
final started = await countdown(3);
print('counted down from $started');
}Three things happen in order:
countdowncreates the completer and starts the timer. The timer does not run yet, because the event loop has not reached it.countdownreturnscompleter.futureimmediately. The Future is still pending.- About 300 ms later, the third tick calls
completer.complete(from). The Future completes with a value, and theawaitinmainresumes.
The Completer API
| Member | What it does |
|---|---|
| `future` | The `Future<T>` that the completer controls. It returns the same object every time. |
| `complete([value])` | Completes the Future with a value. The argument may be a `T` or a `Future<T>`. |
| `completeError(error, [stackTrace])` | Completes the Future with an error. |
| `isCompleted` | `true` once `complete` or `completeError` has been called. |
Two details here cause real bugs:
isCompletedbecomestrueas soon as you callcomplete. This holds even if you passed a Future that is still pending. The completer is "spoken for" at that moment, althoughfuturehas not produced a value yet.- A completer can be completed only once. A second call throws a
StateError.
Wrapping a success and error callback API
Many older APIs take one function for success and another for failure. Here is a stand-in for such an API, followed by a Future-based wrapper.
import 'dart:async';
void loadUser(
int id,
void Function(String name) onSuccess,
void Function(Object error) onError,
) {
Timer(const Duration(milliseconds: 200), () {
if (id < 0) {
onError(ArgumentError.value(id, 'id', 'must not be negative'));
} else {
onSuccess('user-$id');
}
});
}
Future<String> loadUserAsync(int id) {
final completer = Completer<String>();
loadUser(id, completer.complete, completer.completeError);
return completer.future;
}
Future<void> main() async {
print(await loadUserAsync(1));
try {
await loadUserAsync(-1);
} on ArgumentError catch (e) {
print('Failed: ${e.message}');
}
}The output is user-1 and then Failed: must not be negative.
Passing completer.complete and completer.completeError directly works because their optional parameters still fit the callback types. You can also write the callbacks as closures. Use closures when you need to transform the value or add a check first.
Calling code now treats the old API like any other Future. It gets await, try/catch, Future.wait, and timeout without any callback nesting.
Sharing one result with many waiters
A Future can be awaited any number of times, and every waiter gets the same result. This makes a completer useful as a one-time gate. The classic case is "initialization is finished".
import 'dart:async';
class Service {
final _ready = Completer<void>();
Service() {
Timer(const Duration(milliseconds: 300), () {
_ready.complete();
});
}
Future<void> get ready => _ready.future;
Future<String> query(String name) async {
await ready;
return 'result for $name';
}
}
Future<void> main() async {
final service = Service();
final results = await Future.wait([
service.query('a'),
service.query('b'),
]);
print(results);
}Both queries start immediately and both wait on the same gate. After about 300 ms the gate opens and both continue. The program prints [result for a, result for b].
Reporting failure from a repeating callback
Timers and listeners often fire many times. The completer must be completed on exactly one of those firings. Cancel the source as you finish, or it keeps running with nobody listening.
import 'dart:async';
Future<int> pollUntilReady(bool Function() isReady) {
final completer = Completer<int>();
var attempts = 0;
Timer.periodic(const Duration(milliseconds: 100), (timer) {
attempts++;
if (isReady()) {
timer.cancel();
completer.complete(attempts);
} else if (attempts >= 5) {
timer.cancel();
completer.completeError(
TimeoutException('not ready after $attempts attempts'),
);
}
});
return completer.future;
}
Future<void> main() async {
final start = DateTime.now();
final attempts = await pollUntilReady(
() => DateTime.now().difference(start).inMilliseconds > 250,
);
print('ready after $attempts attempts');
try {
await pollUntilReady(() => false);
} on TimeoutException catch (e) {
print(e.message);
}
}The first call usually reports 3 attempts, because the third tick falls after 250 ms. Exact timing depends on scheduling, so do not rely on the number. The second call fails after 5 attempts.
Edge cases and failure modes
Completing twice
A second complete or completeError throws a StateError. This often happens when a callback API can fire more than once, for example an error callback after a success callback. Guard against it when the source is not under your control:
import 'dart:async';
void main() {
final completer = Completer<int>();
completer.complete(1);
print(completer.isCompleted);
if (!completer.isCompleted) {
completer.complete(2);
}
try {
completer.complete(3);
} on StateError catch (e) {
print('StateError: ${e.message}');
}
}The isCompleted check is cheap. Prefer fixing the source of the double call when you can, because it usually signals a logic error.
Never completing
If no code path calls complete or completeError, the Future stays pending forever. Anything that awaits it hangs. Dart does not warn you. Check every path through the callback, including error callbacks, early returns, and listener cancellation. When the source is unreliable, add a deadline with timeout on the returned Future:
final user = await loadUserAsync(7).timeout(const Duration(seconds: 2));A timeout does not stop the underlying work. The timer or listener keeps running, and a late complete call is still legal. It just goes unobserved. Clean up the source yourself if that matters.
Errors with no listener
If you call completeError and nobody has awaited or attached a handler to the Future, the error is reported as unhandled in the current zone. In a plain Dart program that usually terminates the program. Make sure the caller attaches a handler. Alternatively, return completer.future right away so the caller can attach one before the error arrives.
Completing with a Future
completer.complete(otherFuture) makes the completer follow otherFuture. Its own Future finishes when otherFuture does, with the same value or error. Remember that isCompleted is already true at that point, so a later completeError call throws.
Synchronous completion
Completer.sync() runs the waiting code immediately inside the complete call. Normal completers schedule it in a microtask. The synchronous version exists for performance-sensitive library code, and it can cause surprising reentrancy. Use the default constructor unless you have a measured reason.
When not to use a Completer
A completer is the right tool when the result arrives through a callback. It is the wrong tool in these cases:
- You already have a Future. Return it, or use
asyncandawait. Wrapping a Future in a completer only adds code and new ways to forget a failure path. - A one-off delay is enough.
Future.delayedalready does this. - The API produces many values over time. A single Future holds one result. Use a
StreamControllerand return aStream.
Exercises
Exercise
A callback API calls onDone(result) once on success. It may also call onError(e) after onDone in rare cases. Your wrapper completes a Completer in both callbacks. What goes wrong, and how do you fix it?
Show answer
The second call throws a StateError because a completer can complete only once. Guard each call with if (!completer.isCompleted), or fix the API usage so that only one callback can fire.
Exercise
What does this program print, and why does main never finish?
Future<int> compute() {
final completer = Completer<int>();
Timer(const Duration(milliseconds: 100), () {
final value = int.parse('abc');
completer.complete(value);
});
return completer.future;
}
Show answer
int.parse('abc') throws a FormatException inside the timer callback, so complete is never reached. The Future stays pending, and an await compute() hangs. The exception also surfaces as an uncaught error in the zone. Fix it by wrapping the body in try/catch and calling completer.completeError(e, st) in the catch clause.
Exercise
Write Future<void> waitForTimer(Duration d) using a Completer and a Timer. Then say why Future.delayed makes the wrapper unnecessary here.
Show answer
Code: Future<void> waitForTimer(Duration d) { final c = Completer<void>(); Timer(d, c.complete); return c.future; }. Future.delayed(d) already returns a Future that completes after d, so the wrapper adds nothing. A completer is useful only when the result arrives through a callback you do not control.