Sub topic 1
Why Asynchronous Code Exists
Prerequisites
This chapter assumes you know basic Dart syntax, including functions, variables, and types. You should understand callbacks and anonymous functions, and you should be able to run a program with dart run.
Why asynchronous code exists
Some work takes time. Reading a file, calling a web API, or waiting for a timer can each take milliseconds or seconds. If Dart blocked on each of these, the whole app would freeze. Asynchronous code starts the slow work, lets the program keep running, and handles the result when it arrives.
How the event loop orders your code
Dart runs your code on one thread. An event loop decides what runs next, using two queues:
- The microtask queue holds short internal tasks. Dart drains it first.
- The event queue holds external events such as timers and I/O results.
import 'dart:async';
void main() {
print('1 main start');
Future(() => print('4 event queue'));
scheduleMicrotask(() => print('3 microtask'));
print('2 main end');
}The output is 1, 2, 3, 4. Synchronous code finishes first, then the microtasks run, then the event queue.
Futures: values that arrive later
A Future<T> is an object that will hold a value of type T later, or an error. A Future is either uncompleted, completed with a value, or completed with an error.
Creating Futures
Future(() => ...) runs its callback as an event. Future.value(x) creates a Future that is already completed with x. Future.delayed(duration, fn) runs fn after the delay. Future.error(e) creates a Future completed with an error.
void main() {
print('main start');
Future.value(42).then((n) => print('value: $n'));
Future.error('oops').catchError((Object e) => print('error: $e'));
Future.delayed(const Duration(milliseconds: 100), () => print('delayed'));
print('main end');
}main end prints first. The then and catchError callbacks run before delayed, which prints last.
Exercise
In the event-loop example, why does 3 microtask print before 4 event queue?
Show answer
Dart drains the microtask queue before it takes the next event from the event queue, so the microtask runs first even though the event was queued earlier.