Explain it simply
Explain it simply
Think about ordering at a busy coffee counter. You pay, the barista hands you a ticket with a number, and you step aside. You do not stand frozen at the counter until your latte appears; you check your phone, find a table, and when your number is called you swap the ticket for the drink.
In Dart that ticket is a Future. A function that talks to something slow (a file, a server, a timer) hands back a Future immediately, and the real work finishes later. The word await means 'I am done for now, call me back when this ticket is ready'. While your function waits, the rest of the program keeps running, so a Flutter screen keeps animating and a server keeps answering other visitors.
Problem → Why → Solution
The problem: mistaking the ticket for the drink
Here is the first mistake nearly every Dart beginner makes. fetchOrder() is declared async, so calling it does not run to the end and hand back a String. It hands back a Future<String>. If you forget the await and use that value as if it were the drink, one of two things happens.
When you try to use it as a String, the compiler stops you: calling .length on the Future is rejected with the error "The getter 'length' isn't defined for the type 'Future<String>'". When you only print it, nothing stops you: the output is Instance of 'Future<String>', the program carries on, and the real order arrives a moment later with nobody listening.
Future<String> fetchOrder() async {
await Future.delayed(Duration(milliseconds: 100));
return 'Large latte';
}
void main() {
final order = fetchOrder(); // forgot await
print('Order: $order'); // Order: Instance of 'Future<String>'
}Why does Dart hand back a Future?
A function cannot return a value that does not exist yet, and Dart will not freeze the whole program to wait for it. So the function returns a placeholder right away and promises to fill it in later. The type Future<String> keeps that promise visible in the code, which is exactly what lets the compiler catch the mistake in the first case.
Core concept: Futures and the event loop
A Future<T> is an object that stands in for a value of type T that does not exist yet. At any moment it is in one of three states: uncompleted (the work is still going), completed with a value, or completed with an error. It leaves the uncompleted state exactly once and never changes again, which is why you can hand the same Future to several readers.
Dart runs your code on a single thread per isolate, driven by an event loop with two queues. The microtask queue holds tiny jobs that must finish before anything else, such as the continuation after a completed Future. The event queue holds everything coming from outside: timers, file and network results, taps. After main() finishes, the loop drains every microtask, then takes one event, drains microtasks again, and repeats.
| Where | What it holds | Examples |
|---|---|---|
| Synchronous code | The current call stack | main() and ordinary calls |
| Microtask queue | Short follow-up jobs | scheduleMicrotask, Future.microtask |
| Event queue | Events from outside | Timer, Future.delayed, Future(...), I/O |
import 'dart:async';
void main() {
print('1 sync: start');
Future(() => print('5 event: Future()'));
Future.delayed(Duration(milliseconds: 10), () => print('6 event: delayed 10ms'));
scheduleMicrotask(() => print('3 microtask: scheduleMicrotask'));
Future.microtask(() => print('4 microtask: Future.microtask'));
print('2 sync: end of main');
}Reading the code top to bottom, lines 5 and 6 look like they should come first, but the print numbers show the real order. All synchronous code finishes first, then the two microtasks run in order, and only then do the event-queue tasks take their turns.
The async keyword makes the function's return type a Future and wraps a plain return value for you. The await keyword is the part people misread: it does not block the thread. The function pauses at that line, control goes back to the event loop so other work can run, and when the awaited Future completes the function resumes on the line where it stopped. Until its first await, an async function runs synchronously like any other.
Errors travel the same road as values. If the body throws, the returned Future completes with that error, and await rethrows it in the caller, so ordinary try/catch/finally works across async boundaries. A Future that nobody awaits or listens to still fails, but loudly: the error escapes as an unhandled exception and ends the program.
- Calling an async function gives a ticket
- await parks the function, not the thread
- Meanwhile the event loop runs other work
- Future completes: value or error returns
Picture the Future before you await it. Once control passes that line, other code may run, so the world can look slightly different when your function resumes.
General pattern
Future<Result> name(Param param) async {
final value = await slowCall(param);
// a throw here completes the Future with an error
return Result(value);
}
Future<void> main() async {
try {
final result = await name(argument);
} on SomeError catch (e) { /* handle */ }
}An async function declares Future<Result> and may pause at any await. The caller awaits it to get the value and catches failures with try/on/catch.
Order a drink and wait for it
This program places an order, shows that the ticket is a Future, then waits for it. After that it orders two drinks together and finally shows how a failure surfaces. Every await line is a point where the function may pause, so the numbered prints appear in the order you read them.
The delays are tiny (100 ms) so the program finishes quickly, and the output is the same on every run because each print happens after an await inside one function.
Future<String> fetchOrder(String drink) async {
await Future.delayed(Duration(milliseconds: 100));
if (drink.isEmpty) {
throw ArgumentError('drink must not be empty');
}
return 'Large $drink';
}
Future<void> main() async {
print('1. placing order');
final ticket = fetchOrder('latte');
print('2. ticket is a Future, not a String: ${ticket is Future<String>}');
final order = await ticket;
print('3. received: $order');
final both = await Future.wait([fetchOrder('mocha'), fetchOrder('tea')]);
print('4. both finished: $both');
try {
await fetchOrder('');
} on ArgumentError catch (e) {
print('5. failed: ${e.message}');
} finally {
print('6. counter closed');
}
}Code breakdown
- async function and its Future
Future<String> fetchOrder(String drink) async {async lets the body pause at await. The declared type is Future<String>, yet the body returns a plain String; Dart wraps it for you.
- Pausing without blocking
await Future.delayed(Duration(milliseconds: 100));Future.delayed completes only after the given time. The function pauses here, the event loop is free, and nothing else in the program has to wait.
- A throw becomes a failed Future
throw ArgumentError('drink must not be empty');Inside an async function a throw does not crash the caller immediately. It completes the returned Future with an error, and that error appears at whichever await reads the Future.
- Holding the Future
final ticket = fetchOrder('latte');There is no await here, so ticket is the Future itself and the call has only started. That is why print 2 can show that ticket is a Future<String>.
- Resuming with the value
final order = await ticket;The function pauses on this line and resumes when the ticket completes. Now order is a real String, so string methods work on it.
- Starting calls together
final both = await Future.wait([fetchOrder('mocha'), fetchOrder('tea')]);Both calls have already started before the await, so their delays overlap. The result list follows the order of the input list, not the order of finishing.
- Catching the failure
} on ArgumentError catch (e) {await rethrows the stored error right here, so a normal try/on/catch/finally works. finally runs whether or not the order failed.
1. placing order
2. ticket is a Future, not a String: true
3. received: Large latte
4. both finished: [Large mocha, Large tea]
5. failed: drink must not be empty
6. counter closed- The caller reaches the await line
- The function pauses; the event loop is free
- A timer or I/O completes the Future
- The function resumes after the await
Completed with a value
The value becomes the result of the await expression.
Completed with an error
The error is thrown at the await line, where try/catch can see it.
One by one, or together?
Writing one await per line makes the second call start only after the first one finished. That is correct when the second call needs the first result. When the calls are independent, it wastes time. Start both first and await them together and the delays overlap, so the total is about as long as the slowest call.
For two or three Futures of different types you can also write (a(), b()).wait on a record and destructure the result as (x, y), which keeps each type intact. Future.wait suits a list of Futures of the same type.
Future<int> slowDouble(int n) async {
await Future.delayed(Duration(milliseconds: 100));
return n * 2;
}
Future<void> main() async {
// One after another: the second call starts only after the first finished.
final a = await slowDouble(1);
final b = await slowDouble(2);
print('one by one: $a and $b');
// Together: both calls are already running when we start waiting.
final (x, y) = await (slowDouble(3), slowDouble(4)).wait;
print('together: $x and $y');
}Measure it yourself
In this code the first half takes about 200 ms and the second about 100 ms. Exact timings depend on the machine, so measure with a Stopwatch yourself, and keep timings out of any output you compare.
An async function starts immediately
When you call an async function, its body runs immediately on the caller's call stack until it reaches the first await. Only there does it pause and hand the Future back to the caller. If you miss this, print order can look surprising.
Future<void> task() async {
print('task: before await');
await null;
print('task: after await');
}
void main() {
print('main: start');
task();
print('main: after calling task');
}The output order is main: start, task: before await, main: after calling task, task: after await. Even awaiting null defers the rest of task as a microtask, so it runs only after main has finished its synchronous work.
In real projects
In real projects
In a Flutter app every network request, database read and file load returns a Future. The UI thread must keep drawing frames, so the screen code awaits the result and shows a spinner while it is pending; the FutureBuilder widget exists for exactly this pattern. On the server side, a Dart service built on dart:io can handle many requests on one isolate, because each request mostly waits on a database or another service, and while it awaits, the loop serves the next request.
Command-line tools use the same model: File.readAsString(), Process.run() and HttpClient all return Futures. In real code the ticket sometimes fails (timeouts, missing files, no network), so the way you await matters. Put try/catch at the layer that can show a message or retry, and use Future.wait when a screen needs three independent resources at once instead of loading them one by one.
Common mistakes
Common mistakes
Calling an async function without await
Calling saveOrder() without await starts the work, but the caller moves on immediately. In main that means the program can print 'done' before 'saved', and if saveOrder throws later, nobody is there to catch it: Dart reports 'Unhandled exception: Bad state: boom' and the process exits with an error. Await it, or wrap it in unawaited() when fire-and-forget is truly intended.
Using an async callback inside forEach
list.forEach((n) async { await save(n); }) looks as if it waits for every save, but forEach ignores the Futures its callback returns. The line after it runs immediately, before any save has finished. Use a for-in loop with await to go one by one, or Future.wait(list.map(save)) to go together.
Awaiting independent calls one by one
Three requests of 100 ms each take about 300 ms when awaited in sequence but about 100 ms with Future.wait. Only await in sequence when a later call needs the result of an earlier one.
Believing async makes heavy work run in parallel
The async keyword does not move work to another thread. A loop that runs a million times inside an async function keeps the whole event loop busy, so timers and the UI stall until it ends. Heavy CPU work belongs in an isolate, which a later lesson covers.
Best practices
Best practices
- Declare async functions that return nothing as Future<void>, never void, so callers can await them.
- Await a Future, handle it, or pass it to unawaited() on purpose; never drop it by accident.
- Start independent calls first, then await them together.
- Catch errors where you can do something useful, such as retry or show a message, not at every await.
Mini challenge
Check the shelves
Look up how many units of each item are left on a coffee shop's shelf with an async function. Check many items together and list the ones that fell below a limit. Asking for an unknown item must fail with an error.
- fetchStock(item) waits 50 ms and returns the count on the shelf, throwing a StateError for an unknown item
- lowStock(items) takes an optional named parameter limit (default 5) and starts all lookups together
- It returns the names below the limit in the order they were given
- main() prints the result and catches the error message for an unknown item with try/catch
// Shelf data: item name -> units left.
const shelf = {'beans': 12, 'milk': 2, 'cups': 40, 'lids': 3};
Future<int> fetchStock(String item) async {
// TODO: wait 50 ms with Future.delayed
// TODO: throw StateError('unknown item: ...') when the item is not on the shelf
// TODO: otherwise return the count
}
Future<List<String>> lowStock(List<String> items, {int limit = 5}) async {
// TODO: start every lookup first, then wait for all of them together
// TODO: return the names whose count is below limit, keeping the input order
}
Future<void> main() async {
// TODO: print the low stock for beans, milk, cups and lids
// TODO: call lowStock(['beans', 'sugar']) inside try/catch and print the message
}Expected: The first line is Low stock: [milk, lids], the second is Check failed: unknown item: sugar, and the last is With limit 100: [cups].
Show hint
Future.wait(items.map(fetchStock)) returns the counts in the same order as items, so pair them by index and keep the ones below limit. A StateError exposes its text as e.message.
Show solution
const shelf = {'beans': 12, 'milk': 2, 'cups': 40, 'lids': 3};
Future<int> fetchStock(String item) async {
await Future.delayed(Duration(milliseconds: 50));
final count = shelf[item];
if (count == null) {
throw StateError('unknown item: $item');
}
return count;
}
Future<List<String>> lowStock(List<String> items, {int limit = 5}) async {
final counts = await Future.wait(items.map(fetchStock));
return [
for (var i = 0; i < items.length; i++)
if (counts[i] < limit) items[i],
];
}
Future<void> main() async {
final low = await lowStock(['beans', 'milk', 'cups', 'lids']);
print('Low stock: $low');
try {
await lowStock(['beans', 'sugar']);
} on StateError catch (e) {
print('Check failed: ${e.message}');
}
final generous = await lowStock(['cups'], limit: 100);
print('With limit 100: $generous');
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A Future stands in for a value that does not exist yet and completes once, with a value or with an error
- After main() finishes, all microtasks run first and then event-queue tasks run one at a time
- await pauses only its own function, never the thread, and rethrows the error on that line
- Start independent calls with Future.wait, and remember forEach does not wait for async callbacks
Dart language overview — Dart