Dart Async & Futures
Apps constantly wait: for a network response, a file read, a database query, a user's tap. If the program simply stopped while waiting, the UI would freeze. Dart solves this with asynchronous programming: you start an operation, get a Future that represents its eventual result, and carry on. The async and await keywords make such code read almost like normal, step-by-step code.
Futures
A Future<T> is a promise of a value of type T that will be available later — or an error, if the operation fails. A future is either uncompleted or completed (with a value or an error).
Future<String> fetchUsername() {
// Simulate a slow network call
return Future.delayed(const Duration(milliseconds: 100), () => 'flutter_fan');
}
void main() {
print('1. Requesting user...');
fetchUsername().then((name) => print('3. Got: $name'));
print('2. Doing other work meanwhile');
}1. Requesting user...
2. Doing other work meanwhile
3. Got: flutter_fan
main does not wait at fetchUsername(). It registers a callback with then, prints line 2, and the callback runs once the future completes.
async and await
Chaining then callbacks quickly gets messy. Mark a function async and you can use await to pause that function until a future completes — without blocking the rest of the program.
Future<String> fetchUser() =>
Future.delayed(const Duration(milliseconds: 50), () => 'Linh');
Future<int> fetchOrderCount(String user) =>
Future.delayed(const Duration(milliseconds: 50), () => user.length * 3);
Future<void> main() async {
print('Loading...');
final user = await fetchUser();
print('User: $user');
final orders = await fetchOrderCount(user);
print('$user has $orders orders');
print('Done');
}Loading...
User: Linh
Linh has 12 orders
Done
Rules to remember:
| Rule | Example |
|---|---|
await only works inside an async function |
Future<void> load() async { await ... } |
An async function always returns a Future |
Future<int> count() async => 3; |
await unwraps the future's value |
int n = await count(); |
Return Future<void> when there's no result |
Future<void> save() async { ... } |
Errors in async code
If a future completes with an error, await throws it, so you handle it with ordinary try/catch/finally.
Future<double> fetchPrice(String item) async {
await Future.delayed(const Duration(milliseconds: 20));
if (item == 'unicorn') {
throw Exception('Item not found: $item');
}
return 9.99;
}
Future<void> main() async {
for (final item in ['coffee', 'unicorn']) {
try {
final price = await fetchPrice(item);
print('$item costs $price');
} catch (e) {
print('Error: $e');
} finally {
print('Finished $item');
}
}
}coffee costs 9.99
Finished coffee
Error: Exception: Item not found: unicorn
Finished unicorn
Running futures in parallel
Awaiting one future after another is sequential. If the operations are independent, start them all and wait for them together with Future.wait — or, in Dart 3, with a record of futures and .wait.
import 'dart:async';
Future<String> load(String name, int ms) async {
await Future.delayed(Duration(milliseconds: ms));
print(' $name finished');
return name.toUpperCase();
}
Future<void> main() async {
print('Starting three downloads');
final results = await Future.wait([
load('avatar', 90),
load('posts', 30),
load('friends', 60),
]);
print('Results in request order: $results');
final (profile, count) = await (load('profile', 20), Future.value(42)).wait;
print('$profile / $count');
}Starting three downloads
posts finished
friends finished
avatar finished
Results in request order: [AVATAR, POSTS, FRIENDS]
profile finished
PROFILE / 42
The three loads run concurrently, so they finish in order of their delays — but Future.wait returns results in the order you requested them.
The event loop
Dart runs your code on a single thread with an event loop. When nothing synchronous is left to do, it processes queued work: first all microtasks (e.g. completed futures' callbacks), then the next event (timers, I/O, taps).
import 'dart:async';
void main() {
print('A: synchronous');
Future(() => print('D: event queue'));
scheduleMicrotask(() => print('C: microtask'));
Future.value(1).then((_) => print('C2: then on completed future'));
print('B: still synchronous');
}A: synchronous
B: still synchronous
C: microtask
C2: then on completed future
D: event queue
Tip: Because Flutter's UI also runs on this event loop, never run long CPU-heavy work synchronously in a widget — it blocks frames. Use
asyncfor I/O, and anIsolate(computein Flutter) for heavy computation.
Async in Flutter
You will use futures in Flutter for HTTP requests, reading files, SharedPreferences, showing dialogs (await showDialog(...) returns the user's choice) and navigation (await Navigator.push(...) returns a result from the next screen). The FutureBuilder widget rebuilds the UI when a future completes — see the FutureBuilder & Async UI lesson.
Test yourself
What does an async function always return?
- void
- A Future
- A Stream
- The awaited value
Where can you use await?
- Anywhere
- Only in
main - Only inside
asyncfunctions - Only inside classes
In which order does Future.wait([a, b]) return its results?
- Order of completion
- Order the futures were passed in
- Random order
- Reverse order