Sub topic 1
Why asynchronous code exists
Some operations take far longer than the code around them. Reading a file, calling a web service, or waiting for a timer can take milliseconds or seconds, while a single Dart statement takes nanoseconds. This chapter explains why Dart has asynchronous code, what problem it solves, and what it does not solve. Later chapters cover the mechanics: the event loop, Future, async, and await.
Prerequisites
This chapter assumes you already know:
- Basic Dart syntax: functions, variables, and types.
- Generics such as
List<int>, because you will seeFuture<String>and similar types. - How to run a Dart program with
dart run. - Callbacks and anonymous functions, meaning functions you pass as values to other functions.
You do not need any prior knowledge of Future, async, or threads.
Synchronous code and its limit
Synchronous code runs one statement at a time, in order. Each statement must finish before the next one starts. That is easy to reason about, and for most work it is exactly what you want.
The trouble starts when a statement has to wait for something outside your program. While it waits, the CPU has nothing to do for your program, yet nothing after that statement can run. This is called blocking.
The following program blocks on purpose. The sleep function from dart:io pauses the whole program.
import 'dart:io';
void main() {
print('start');
sleep(const Duration(seconds: 2));
print('end');
}Run it with dart run. You see start, then nothing for two seconds, then end. For a command-line script this is harmless. In a Flutter app it is a serious bug.
Why blocking hurts in a Flutter app
A Flutter app has to draw a new frame many times per second. At 60 frames per second, each frame has a budget of about 16 milliseconds. At 120 frames per second, the budget is about 8 milliseconds. Your Dart code that responds to taps, builds widgets, and updates state runs on the same thread that prepares those frames.
If that code blocks for 2 seconds, the app cannot respond to taps, animations freeze, and the operating system may show a "not responding" warning. A network request commonly takes 100 ms to several seconds, so it must not be written as a blocking call.
Dart's answer: one thread, many waiting tasks
Dart's model is that your code runs on a single thread, and operations that must wait do not block that thread. Instead you start the operation and say what should happen when it finishes. In the meantime the thread is free to run other code. This is asynchronous programming.
Here is the same idea in Dart, using the first example from the plan, a function that returns its result later.
Future<String> fetchGreeting() {
return Future.delayed(const Duration(seconds: 1), () => 'Hello');
}
Future<void> main() async {
print('before');
final greeting = await fetchGreeting();
print(greeting);
print('after');
}The output is before, a pause of about one second, then Hello and after. The code reads top to bottom like the blocking version. The difference is that during the one-second wait, the thread is not stuck. Dart can run other work, such as handling a tap or redrawing a frame. The details of how it does this are the subject of the next chapter. For now, treat await as "pause this function here, let other code run, and resume when the value is ready".
Two tasks waiting at the same time
The benefit becomes clear when two things wait together. In this program, task A needs 300 ms and task B needs 100 ms.
Future<void> task(String name, int milliseconds) async {
print('$name: start');
await Future<void>.delayed(Duration(milliseconds: milliseconds));
print('$name: done');
}
Future<void> main() async {
final a = task('A', 300);
final b = task('B', 100);
await a;
await b;
print('all finished');
}The output is:
A: start
B: start
B: done
A: done
all finishedBoth tasks started before either finished. B finished first because its wait was shorter. The whole program took about 300 ms, not 400 ms, because the two waits overlapped. If each task had used a blocking sleep, the total would be 400 ms and A would always finish before B starts.
Notice that this used one thread. Nothing ran at the same instant. The waiting overlapped, and only the waiting.
Concurrency is not parallelism
Two terms are often confused, and the difference matters for the rest of this tutorial.
- Concurrency means several tasks are in progress during the same period. Their steps may be interleaved on one thread.
- Parallelism means several tasks are literally executing at the same instant, on different CPU cores.
Dart's Future and async/await give you concurrency on one thread. They do not give you parallelism. Dart reaches parallelism through isolates, which are separate workers with their own memory. The final chapters of this tutorial cover Isolate.run for that purpose.
Dart's single-threaded model has a useful side effect. Within one isolate, two pieces of your code never run at the same moment, so you do not need locks around ordinary variables. A function can only be interrupted at an await, which you can see in the source.
What kind of waiting needs async code
Asynchronous code helps when the program is waiting for something other than its own computation. Typical sources of waiting are:
- Network requests, such as calling a REST API.
- File and database access.
- Timers and delays.
- User input, such as a tap or a keystroke.
- Messages from another isolate or from the platform, such as a plugin reading the device's location.
In all of these, the work happens outside your Dart code, in the operating system, on a remote server, or in another isolate. Your code only needs to be told when the result is ready.
The cost of the old approach: callbacks
Asynchronous APIs existed long before async and await. The classic form is a callback, a function you pass in and that the system calls later. Here is a made-up callback-style API and a use of it.
void loadUser(int id, void Function(String name) onDone) {
Future<void>.delayed(const Duration(milliseconds: 100), () {
onDone('user$id');
});
}
void main() {
loadUser(1, (name) {
print('got $name');
loadUser(2, (other) {
print('got $other');
});
});
}This works, but each dependent step adds another level of nesting. Add error handling at every level and the code becomes hard to read. Dart's Future type represents "a value that will arrive later" as an ordinary object, and async/await lets you write the same logic in a straight line. You will convert code like this in a later chapter.
What async code does not fix
Intermediate programmers most often go wrong by assuming that marking a function async makes it run elsewhere or run faster. It does neither.
CPU-bound work still blocks
The event loop can only switch tasks when your code gives it a chance, at an await or when a function returns. A long loop never gives up the thread, even inside an async function.
import 'dart:async';
Future<void> main() async {
final sw = Stopwatch()..start();
Timer(const Duration(milliseconds: 100), () {
print('timer fired after ${sw.elapsedMilliseconds} ms');
});
var total = 0;
for (var i = 0; i < 1000000000; i++) {
total += i;
}
print('loop finished after ${sw.elapsedMilliseconds} ms, total $total');
await Future<void>.delayed(const Duration(milliseconds: 200));
}The timer asks to fire after 100 ms. It actually fires only after the loop ends, so the printed time is far above 100 ms. The exact number depends on your machine, but the order is always the same: loop finished is printed first, then timer fired. The loop kept the thread busy, so the timer's callback had to wait its turn.
In a Flutter app, a loop like this would freeze the screen. The remedy for CPU-bound work is not async. It is moving the work to another isolate, which is covered in the last chapter.
Blocking calls undo the benefit
Calls such as sleep or the synchronous file methods (readAsStringSync, writeAsStringSync) block the thread for their whole duration. In a Flutter app, prefer the asynchronous versions (readAsString, writeAsString) so the UI stays responsive. In a short command-line script, the synchronous versions are often fine and simpler.
Async spreads through your call chain
A function that needs the result of an asynchronous operation must either wait for it with await (and so become async itself) or hand the pending result onward as a Future. This is why asynchronous types appear in many signatures in a codebase. The return type changes from String to Future<String>, and the callers must deal with that.
Summary of the model
The table below compares the three approaches you have now seen.
| Approach | Thread while waiting | Readability | Good for |
|---|---|---|---|
| Blocking (synchronous) call | Stuck until the operation ends | Simple, linear | Short scripts, startup code |
| Callbacks | Free to run other code | Nests quickly, hard to handle errors | Older APIs, event notifications |
| `Future` with `async`/`await` | Free to run other code | Linear, like synchronous code | Most waiting operations in modern Dart |
The diagram shows one thread with a long wait, first blocking and then asynchronous.
Common mistakes at this stage
- Believing
asynccreates a new thread. It does not. Everything still runs on one thread per isolate. - Expecting an
asyncfunction with a heavy loop to leave the UI responsive. - Using a blocking call such as
sleepinside code that runs in a Flutter UI. - Assuming that two
awaitcalls in a row overlap. Eachawaitfinishes before the next line runs, so the second wait starts only after the first ends. In the task example above, the overlap happened because both tasks were started before the firstawait. Later chapters return to this under sequential and parallel work.
Exercise
In the two-task example, task('A', 300) and task('B', 100) are both started before the first await. Suppose you rewrite main as await task('A', 300); await task('B', 100);. What is the output order, and about how long does the program take?
Show answer
The output is A: start, A: done, B: start, B: done, then all finished. B does not start until A has completely finished, so the waits do not overlap and the program takes about 400 ms (300 + 100) instead of about 300 ms.
Exercise
A Flutter button handler runs an async function that contains a for loop of two billion additions and no await inside the loop. Will the app stay responsive during the loop? Explain, and name the Dart tool that fits this kind of work.
Show answer
No. The loop is CPU-bound and never yields the thread, so the event loop cannot handle taps or draw frames until the loop ends, even though the function is marked async. Async code helps only with waiting. For heavy computation, run the work in another isolate with Isolate.run, which returns the result as a Future.