Sub topic 1
Why Asynchronous Code Exists
A Dart program often needs to wait for work outside the program itself. Common examples include reading a file, calling a web service, querying a database, or waiting for a timer. These operations can take an unpredictable amount of time.
If your program waits by blocking its main execution path, it cannot do useful work during that time. In a Flutter app, blocking the main isolate can prevent frames from being drawn. The screen may stop responding, animations may freeze, and the operating system may report that the app is unresponsive.
Prerequisites
This chapter assumes that you know basic Dart functions, variables, types, callbacks, and generic types such as List<int>. You should also know how to run a Dart program with dart run.
Synchronous and asynchronous work
Synchronous code runs one statement at a time. Each statement must finish before the next statement starts.
void main() {
print('start');
final total = 2 + 3;
print('total: $total');
print('end');
}The output is predictable:
start
total: 5
endThis model is useful for quick calculations. It becomes a problem when one operation waits on a slow external resource. A synchronous network request, for example, could stop all other work until the server responds.
Asynchronous code starts an operation and allows the program to continue. When the operation finishes, Dart runs code that handles its result. The program can therefore keep processing input, drawing frames, or handling other completed operations.
Future<String> fetchGreeting() {
return Future.delayed(
const Duration(seconds: 1),
() => 'Hello',
);
}
Future<void> main() async {
print('1. start');
final greetingRequest = fetchGreeting();
print('2. request started');
print('3. other work can run now');
final greeting = await greetingRequest;
print('4. response: $greeting');
}The delayed operation takes about one second, but the program prints the first three messages immediately. await then pauses this function until the result is ready. It does not freeze the Dart isolate or the Flutter interface.
A Future<T> represents a result that will be available later. Future<String> means that the eventual result is a String. The details of creating and combining Futures come later. For now, focus on the reason they exist: they represent waiting without blocking the whole program.
Dart's event loop
Dart normally runs application code in one isolate. An isolate has its own memory and execution path. Its event loop repeatedly checks for work, runs a piece of code, and then checks again.
When asynchronous code starts an external operation, the event loop can process other work while that operation is pending. After the operation completes, its result is scheduled for processing.
This does not make every operation faster. The server still takes the same time to respond. Asynchronous code improves responsiveness because the program does not waste its main execution path waiting.
Choosing asynchronous code
Use asynchronous code when the operation has an uncertain or substantial delay. Typical examples include:
- HTTP requests
- Database queries
- File access
- Timers
- Platform API calls
- Reading a stream of events
Keep small, immediate calculations synchronous. Adding asynchronous control flow to a simple expression makes the code harder to read without improving responsiveness.
The next chapters explain how Dart schedules asynchronous callbacks, how Futures represent success or failure, and how async and await make asynchronous code easier to read.
Exercise
Why can a network request be asynchronous even when Dart runs application code on one isolate?
Show answer
The isolate starts the request and returns to its event loop instead of blocking. When the request completes, Dart schedules code to handle the result.