Sub topic 14
Asynchronous Code with `Future`, `async`, and `await`
This chapter assumes you know Dart functions, classes, exceptions, and basic control flow. It also assumes you can run a Dart program from a terminal.
Why asynchronous code matters
Some operations take time:
- Reading a file
- Calling a web service
- Loading data from a database
- Waiting for a timer
If a program waits synchronously, it cannot do other work during that time. Asynchronous code lets the program start a slow operation and continue running. Dart uses a Future to represent a value that will be available later.
A Future<String> means “a string that will arrive later.” A Future<void> means “an operation that will finish later without producing a value.”
Declaring asynchronous functions
Add async to a function that performs asynchronous work. Such a function returns a Future, even when its body returns an ordinary value.
Use await inside an async function to wait for a Future. The await expression produces the Future's eventual value.
Future<String> loadGreeting() async {
await Future.delayed(const Duration(milliseconds: 300));
return 'Hello from Dart';
}
Future<void> main() async {
print('Loading...');
final greeting = await loadGreeting();
print(greeting);
print('Finished');
}The main function is also marked async, so it can use await. The program prints Loading..., waits briefly, and then prints the greeting.
Without await, loadGreeting() returns immediately with a Future<String>, not a String:
final result = loadGreeting(); // Future<String>Trying to use result as a string is a type error. Use await loadGreeting() when you need the completed value.
Handling failures
An asynchronous operation can fail. An exception raised inside a Future is delivered when the Future is awaited. Handle it with the same try, on, catch, and finally syntax used for synchronous code.
Future<String> fetchUserName() async {
await Future.delayed(const Duration(milliseconds: 100));
throw StateError('The service is unavailable');
}
Future<void> main() async {
try {
final name = await fetchUserName();
print(name);
} on StateError catch (error) {
print('Could not load the user: ${error.message}');
} finally {
print('Request finished');
}
}A common error is forgetting to await a Future. Another is catching an error around the function call but not awaiting it. Put await inside the try block so the asynchronous failure is caught.
Running independent work
When operations do not depend on each other, start them before awaiting either one. This allows them to run concurrently.
Future<String> loadProfile() async {
await Future.delayed(const Duration(milliseconds: 200));
return 'Profile';
}
Future<String> loadSettings() async {
await Future.delayed(const Duration(milliseconds: 200));
return 'Settings';
}
Future<void> main() async {
final profileFuture = loadProfile();
final settingsFuture = loadSettings();
final profile = await profileFuture;
final settings = await settingsFuture;
print('$profile and $settings loaded');
}Awaiting loadProfile() before starting loadSettings() would make the total wait longer. Do not run operations concurrently when the second operation needs the first operation's result.
Exercise
What type does loadGreeting() return before it is awaited, and what type does await loadGreeting() produce?
Show answer
The function call returns a Future<String>. Awaiting it produces the completed String.