Sub topic 10
Common mistakes and how to avoid them
This chapter assumes you can write async functions and use await, know that a Future completes with a value or an error, and understand that Dart runs your code on a single-threaded event loop. Most async bugs in Dart come from a few patterns. Each one compiles and often appears to work, which is why it helps to know their symptoms.
Mistakes at a glance
| Mistake | Typical symptom | Fix |
|---|---|---|
| Missing `await` | Output shows `Instance of 'Future<int>'`, or code runs before the data exists | Add `await`, or deliberately keep the Future |
| Unawaited Future | Work finishes after the caller moved on, or an error crashes the app later | `await` it, or mark it with `unawaited` and handle errors |
| `return future` inside `try` | The `catch` block never runs | Use `return await future` |
| `forEach` with an async callback | Code after the loop runs before the loop's work | Use `for`/`await`, or `Future.wait` |
| Heavy synchronous work in an async function | Timers and UI events are delayed | Move the work to `Isolate.run` |
| State assumed unchanged after `await` | Stale or duplicated updates | Re-check state after each `await` |
Forgetting to await
Calling an async function without await gives you the Future itself, not its result.
Future<int> loadCount() =>
Future.delayed(const Duration(milliseconds: 100), () => 7);
Future<void> main() async {
final forgotten = loadCount();
print('Count: $forgotten');
final count = await loadCount();
print('Count: $count');
}The first line prints Count: Instance of 'Future<int>'. The second prints Count: 7. String interpolation accepts any object, so the compiler stays quiet.
The type system catches many other cases. In if (isLoggedIn()) where isLoggedIn returns Future<bool>, the condition is not a bool, so the analyzer reports an error. Arithmetic on a Future<int> fails the same way. When the type checker reports a Future where you expected a plain value, check for a missing await first.
Methods called on the result are another trap. loadCount().toString() compiles, but it describes the Future instead of the number.
Unawaited Futures
If you call a Future-returning function and ignore the result, Dart does not wait for it. The caller continues immediately.
import 'dart:async';
Future<void> save(String name) async {
await Future<void>.delayed(const Duration(milliseconds: 200));
print('saved $name');
}
Future<void> main() async {
save('profile');
print('main finished');
}This prints main finished first. saved profile appears later, because the Dart process stays alive until pending events finish. In a server or Flutter app, the caller may continue as if the data were saved when it was not. In a unit test, the test can finish before the work does.
Sometimes you want fire-and-forget work, such as sending analytics. Make that choice explicit with unawaited from dart:async, and attach an error handler:
import 'dart:async';
Future<void> sendAnalytics(String event) async {
await Future<void>.delayed(const Duration(milliseconds: 100));
throw StateError('analytics server unreachable');
}
Future<void> main() async {
unawaited(
sendAnalytics('app_opened').catchError((Object e) {
print('analytics failed: $e');
}),
);
print('continuing without waiting');
await Future<void>.delayed(const Duration(milliseconds: 300));
}unawaited does nothing at runtime. It tells readers and the analyzer that ignoring the Future is intentional.
Errors with no listener
An error in a Future that nobody awaits or listens to is not lost. It becomes an uncaught error in the current zone. In a plain Dart program, the isolate terminates with the error. In Flutter, the framework reports it and the app usually keeps running, but the failure is no longer connected to the code that caused it. A try/catch around the call does not help, because the call returned normally and the error arrives later.
The rule is that every Future should be awaited, returned to a caller, or given an error handler.
Let the analyzer find them
Add these lints to analysis_options.yaml:
linter:
rules:
- unawaited_futures
- discarded_futuresunawaited_futures reports Futures ignored inside async functions. discarded_futures reports Future-returning calls inside non-async functions, where there is nothing to await with.
`return` without `await` inside `try`
This mistake is easy to miss because it looks correct.
Future<String> fetchData() async {
throw Exception('network down');
}
Future<String> withoutAwait() async {
try {
return fetchData();
} catch (e) {
return 'fallback';
}
}
Future<String> withAwait() async {
try {
return await fetchData();
} catch (e) {
return 'fallback';
}
}
Future<void> main() async {
print(await withAwait());
try {
print(await withoutAwait());
} catch (e) {
print('caller caught: $e');
}
}The output is fallback, then caller caught: Exception: network down.
In withoutAwait, return fetchData() hands the unfinished Future to the function's own result and leaves the try block immediately. The error happens later, after the try has been exited, so the catch never sees it. Writing return await makes the function wait inside the try, so the error is thrown where catch can see it.
Outside a try block, return await adds nothing, and the unnecessary_await_in_return lint may flag it. Inside try/catch/finally, keep it. The finally block has the same issue: without await, it runs before the Future completes.
Async callbacks passed to `forEach`
List.forEach ignores what its callback returns. If the callback is async, the returned Futures are discarded.
Future<void> main() async {
final ids = [1, 2, 3];
ids.forEach((id) async {
await Future<void>.delayed(const Duration(milliseconds: 100));
print('done $id');
});
print('after forEach');
await Future<void>.delayed(const Duration(milliseconds: 300));
}after forEach prints first, then the three done lines. Nothing waited for the work. The same applies to Iterable.map if you never consume the result, because map is lazy and does not even start the work.
Choose one of two fixes. For one item at a time, in order, use a loop:
for (final id in ids) {
await process(id);
}For all items at once, use Future.wait:
await Future.wait(ids.map(process));Here process is any function of type Future<void> Function(int). A for loop with await is also the right choice when each step depends on the previous one, or when you must limit how many operations run at once.
Treating `async` as threading
Marking a function async does not move it to another thread. Code runs on the event loop until it reaches an await. A long synchronous loop blocks everything else, including timers and, in Flutter, frame rendering.
import 'dart:async';
Future<void> main() async {
final sw = Stopwatch()..start();
Timer(const Duration(milliseconds: 100), () {
print('timer fired at ${sw.elapsedMilliseconds} ms');
});
var total = 0;
for (var i = 0; i < 300000000; i++) {
total += i;
}
print('loop finished at ${sw.elapsedMilliseconds} ms, total $total');
}The timer was due after 100 ms but fires only after the loop finishes. The loop took however long it took, and the event queue waited. Wrapping the loop in an async function changes nothing. For CPU-heavy work, use Isolate.run, covered in the last chapter of this tutorial. For work that is merely long but divisible, you can also yield to the event loop between chunks with await Future<void>.delayed(Duration.zero).
Assuming state is unchanged after `await`
Every await is a point where other code can run. If you read a value, await something, and then write based on the old value, another task may have changed it in between.
int balance = 100;
Future<void> withdraw(int amount) async {
if (balance >= amount) {
await Future<void>.delayed(const Duration(milliseconds: 50));
balance -= amount;
}
}
Future<void> main() async {
await Future.wait([withdraw(80), withdraw(80)]);
print(balance);
}Both calls pass the check while the balance is still 100, so the result is -60. Dart has no data races between threads here, but it still has logical races across await points. Re-check conditions after the await, or perform the check and the update in the same synchronous stretch of code. In Flutter, the same idea applies to widgets: after an await, check mounted before using a BuildContext or calling setState.
Other errors to watch for
awaitin a non-async function. The compiler rejects this. Addasyncto the function and change its return type toFuture<T>.- A
voidreturn type on async functions.void doWork() async {...}gives callers nothing to await, and errors escape. UseFuture<void>. The usual exception ismain, and even thereFuture<void> main() asyncis clearer. - Async closures passed as
void Function(). A callback such asonPressed: () async { ... }is accepted, but its Future is dropped. Put atry/catchinside the closure so errors are handled in place. Future.waitand failures. By default it waits for every Future, then reports the first error. WitheagerError: trueit fails at the first error, but the other operations keep running.- Swallowing errors with an empty
catch. Log or rethrow. A silentcatch (_) {}turns a visible failure into missing data.
A quick debugging flow
When async code behaves out of order or seems to skip work, walk through these questions.
Exercises
Exercise
This function is meant to return 'cached' when fetchRemote() fails, but callers see the exception instead. Why, and what is the fix?
Future<String> load() async {
try {
return fetchRemote();
} catch (_) {
return 'cached';
}
}
Show answer
return fetchRemote() returns the Future without waiting for it, so the function leaves the try block before the error occurs. The error then completes the function's own Future, and the catch is skipped. Change it to return await fetchRemote(); so the error is thrown inside the try.
Exercise
A loop calls items.forEach((item) async { await upload(item); }); and then prints 'All uploaded'. The message appears before the uploads finish. Rewrite the loop so the message prints only after every upload completes, with all uploads running at the same time.
Show answer
Replace the loop with await Future.wait(items.map(upload)); and print the message afterwards. map produces one Future per item, and Future.wait completes when all of them have finished. If uploads had to run one after another, use for (final item in items) { await upload(item); } instead.
Exercise
You want to log an event without making the user wait. Which two things should you do so the call is both intentional and safe?
Show answer
Wrap the call in unawaited(...) to show that ignoring the Future is deliberate, and attach an error handler such as .catchError(...), or handle errors inside the called function, so a failure does not become an uncaught error.