Sub topic 10
Common mistakes and how to avoid them
This chapter assumes you know basic Dart syntax, callbacks, generics such as List<int>, and how to run a program with dart run. It also assumes you have used Future, async, and await.
Asynchronous code often fails quietly because a Future represents work that has not finished yet. The code can look correct while its result or error is handled too late.
Mistake: forgetting `await`
Calling an asynchronous function returns a Future, not the final value. Use await when the next statement needs that value.
Future<String> fetchUserName() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
return 'Mina';
}
Future<void> main() async {
final nameFuture = fetchUserName();
print(nameFuture.runtimeType); // Future<String>
final name = await fetchUserName();
print(name); // Mina
}A missing await can cause type errors, display a Future instead of useful data, or let later code run before the operation finishes.
Mistake: assuming `try` catches an unawaited error
A try block catches an asynchronous error only if the failing Future is awaited inside the block. Returning a Future immediately passes its eventual error to the caller.
Future<String> fetchData() async {
throw Exception('network down');
}
Future<String> loadWithFallback() async {
try {
return await fetchData();
} catch (error) {
return 'fallback';
}
}
Future<void> main() async {
print(await loadWithFallback()); // fallback
}The return await is important here. It makes the try block wait for the operation, so its catch clause can handle the error.
Mistake: starting work without handling it
An unawaited Future continues running after the current function moves on. This can be intentional, such as sending analytics, but errors still need an owner.
Dart provides unawaited in dart:async to document intentional fire-and-forget work. It does not handle errors by itself.
import 'dart:async';
Future<void> saveDraft() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
throw Exception('save failed');
}
void startBackgroundSave() {
unawaited(
saveDraft().catchError((error) {
print('Background save error: $error');
}),
);
}
Future<void> main() async {
startBackgroundSave();
await Future<void>.delayed(const Duration(milliseconds: 200));
}Use await when the caller must know whether the operation succeeded. Use unawaited only when the operation may continue independently and has its own error handling.
Mistake: confusing sequential and parallel work
Awaiting independent operations one by one makes them sequential. Start both futures first, then use Future.wait to wait for both.
| Goal | Suitable pattern |
|---|---|
| The second operation needs the first result | `await` operations in sequence |
| Operations are independent | `Future.wait` |
Future<int> loadScore() async {
await Future<void>.delayed(const Duration(milliseconds: 300));
return 80;
}
Future<String> loadGrade() async {
await Future<void>.delayed(const Duration(milliseconds: 300));
return 'B';
}
Future<void> main() async {
final results = await Future.wait<Object>([
loadScore(),
loadGrade(),
]);
print('score: ${results[0]}, grade: ${results[1]}');
}Future.wait fails when one of its futures fails unless you choose a different error-handling design.
A reliable decision process
Checklist
- Check whether a variable contains a value or a
Future<value>. - Put
awaitinsidetrywhen thattrymust catch the asynchronous error. - Do not ignore a future accidentally.
- Use
unawaitedonly for deliberate background work. - Use
Future.waitfor independent operations. - Give every asynchronous error a clear handler.
Exercise
Why does try { return fetchData(); } catch (e) { ... } usually fail to catch an error from fetchData()?
Show answer
The function returns the Future before that Future completes. Use return await fetchData() inside the try block so the error is thrown where the catch clause can handle it.