What is a Dart Completer and when should you use it?
This tests bridging callback APIs into Dart's Future ecosystem. An answer defines Completer as a manual Future producer, explains completing with value or error from callbacks, preferring Future() when possible. A red flag is using Completer for simple async.
WHAT THIS TESTS: This question probes whether you understand the boundary between Dart's Future-based async model and legacy callback-style APIs. Specifically, it checks if you know how to manually create and resolve a Future when the standard Future constructors or async/await sugar cannot bridge an external callback system.
A GOOD ANSWER COVERS: First, a crisp definition: Completer is a class in dart:async that acts as a manual factory for a Future. You expose its future property to callers immediately, then resolve it later via complete(value) or completeError(error, stackTrace). Second, the canonical use case: wrapping a callback-based API, such as a native platform channel, an older HTTP client, or a third-party SDK that emits results through onSuccess and onFailure handlers. Third, the critical caveat that Completer is a tool of last resort for Future creation; you should prefer Future(() => ...) or chaining then() when the async flow is already under your control. Fourth, mention of isCompleted to guard against double-completion, which can throw a StateError.
COMMON WRONG ANSWERS: A major red flag is suggesting Completer for routine async work like network requests or file I/O where Future and async/await are cleaner. Another mistake is forgetting to handle error paths, leaving the Completer's future dangling forever if the callback signals failure. Some candidates also miss that calling complete twice throws, so they do not mention defensive checks or careful lifecycle management.
LIKELY FOLLOW-UPS: The interviewer may ask how you would cancel or timeout a Completer-based operation. They might also probe thread safety or isolate boundaries, since Completers should not be sent across isolates if they hold VM-unsendable state. Another common follow-up is asking how to convert a Stream into a Future, which can sometimes be done with Completer but is better handled with Stream.first or similar.
ONE CONCRETE EXAMPLE: Imagine wrapping an Android Location Services API that calls onLocationChanged with a location object and onError with a message. You create a Completer of Location inside a method, return completer.future immediately, and inside the callbacks invoke completer.complete(location) or completer.completeError(Exception(msg)). You also check completer.isCompleted before calling complete to avoid crashes from duplicate callbacks.
Read the original → api.flutter.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.