Sub topic 11
Bridging callbacks to Futures with Completer
This chapter assumes you know Dart functions, callbacks, generics, and how to run a Dart program with dart run. It also assumes you understand that a Future<T> represents one result that becomes available later.
Many Dart APIs already return Futures. Some older or lower-level APIs report results through callbacks instead:
startOperation(
onSuccess: (value) => print(value),
onError: (error) => print(error),
);A Completer<T> adapts this callback style to a Future<T>. You return the completer's future immediately, then complete it later when the callback reports success or failure.
How a Completer works
A completer has two important parts:
completer.futureis the Future that callers await.completer.complete(value)finishes that Future with a value.completer.completeError(error, stackTrace)finishes it with an error.
The Future must be completed exactly once. Completing it twice causes a StateError.
The following function wraps a callback-based countdown. The timer calls a callback repeatedly, but the caller receives one Future when the countdown finishes.
import 'dart:async';
void startCountdown(
int from, {
required void Function(int value) onTick,
required void Function() onDone,
}) {
var current = from;
final timer = Timer.periodic(const Duration(milliseconds: 200), (timer) {
onTick(current);
current--;
if (current == 0) {
timer.cancel();
onDone();
}
});
}
Future<int> countdown(int from) {
final completer = Completer<int>();
startCountdown(
from,
onTick: (value) => print('remaining: $value'),
onDone: () => completer.complete(from),
);
return completer.future;
}
Future<void> main() async {
final startedFrom = await countdown(3);
print('finished countdown from $startedFrom');
}countdown returns before the timer finishes. The caller can still use normal Future syntax:
final value = await countdown(3);The callback eventually calls complete, which allows the await expression to continue.
Completing with success or failure
A callback API might report either a result or an error. Map those two paths to complete and completeError.
import 'dart:async';
void readSetting(
String key, {
required void Function(String value) onSuccess,
required void Function(Object error, StackTrace stackTrace) onError,
}) {
Timer(const Duration(milliseconds: 100), () {
if (key == 'theme') {
onSuccess('dark');
} else {
onError(
ArgumentError('Unknown setting: $key'),
StackTrace.current,
);
}
});
}
Future<String> loadSetting(String key) {
final completer = Completer<String>();
readSetting(
key,
onSuccess: completer.complete,
onError: completer.completeError,
);
return completer.future;
}
Future<void> main() async {
try {
print(await loadSetting('theme'));
print(await loadSetting('language'));
} catch (error) {
print('Could not load setting: $error');
}
}The error keeps its asynchronous nature. await rethrows it, so ordinary try, on, catch, and finally blocks can handle it.
| Callback event | Completer action | Future result |
|---|---|---|
| Operation succeeds | `complete(value)` | Completes with a value |
| Operation fails | `completeError(error)` | Completes with an error |
| Operation reports twice | A second completion | `StateError` |
Important design decisions
A completer is useful when you must bridge an API that you cannot change. It is usually unnecessary when you control the operation, because an async function is simpler.
Protect the Future from callbacks that might fire more than once. You can check isCompleted before completing, although fixing the callback API is usually better.
void finishOnce<T>(Completer<T> completer, T value) {
if (!completer.isCompleted) {
completer.complete(value);
}
}For subscriptions, timers, sockets, or UI resources, also consider cancellation and cleanup. A Future alone cannot cancel the underlying operation. If the caller needs cancellation, return a separate controller or define an API that supports it.
Exercise
Why should a wrapper call completeError instead of throwing an error directly inside a later callback?
Show answer
The callback runs after the wrapper has returned. completeError delivers the failure through the returned Future, so the caller can handle it with await and try/catch.