Dart async/await
Dart async and await
In the previous chapter, you used then() to get the value of a future.
The keywords async and await give you an easier way to do the same thing.
With them, async code looks almost like normal code that runs from top to bottom.
asyncmarks a function as asynchronous.awaitwaits for a future to complete and gives you its value.
You can only use await inside a function that is marked with async.
Using await
To use await in main(), add async after the parentheses and change the return type to Future<void>:
Example
Future<void> main() async {
print('Ordering a pizza...');
String food = await Future.delayed(Duration(seconds: 1), () => 'Pizza');
print('Your $food is ready');
}
Try it Yourself »
Result:
Ordering a pizza...
Your Pizza is ready
The line with await pauses the function until the future is done.
Then the value of the future ('Pizza') is stored in the variable food.
While the function is paused, Dart is free to run other code, so the program does not freeze.
If you use await in a function without async, the program does not run:
Result:
main.dart:2:17: Error: 'await' can only be used in 'async' or 'async*' methods.
String food = await Future.value('Pizza');
^^^^^
Write Your Own async Function
An async function always returns a future.
If the function returns a String, the return type is Future<String>.
If the function returns nothing, the return type is Future<void>:
Example
Future<String> getUserName() async {
await Future.delayed(Duration(seconds: 1));
return 'Liam';
}
Future<void> main() async {
print('Loading user...');
String name = await getUserName();
print('Hello, $name');
}
Try it Yourself »
Result:
Loading user...
Hello, Liam
Inside the function, you write return 'Liam', and Dart wraps the value in a future for you.
Notice that Future.delayed() without a function just waits, like a pause.
Errors With try/catch
When you use await, you can handle errors with a normal try and catch block.
If the future fails, await throws the error, and the catch block runs:
Example
Future<int> getStock(String fruit) async {
await Future.delayed(Duration(seconds: 1));
if (fruit == 'mango') {
throw Exception('No mangos today');
}
return 12;
}
Future<void> main() async {
try {
int apples = await getStock('apple');
print('Apples: $apples');
int mangos = await getStock('mango');
print('Mangos: $mangos');
} catch (e) {
print('Error: $e');
} finally {
print('Done checking');
}
}
Try it Yourself »
Result:
Apples: 12
Error: Exception: No mangos today
Done checking
The line print('Mangos: $mangos') did not run, because the error jumped straight to the catch block.
One After Another
When you await one future after another, each task starts only when the one before it is finished.
This is called running tasks sequentially.
A Stopwatch measures how long the code takes:
Example
Future<String> cook(String dish, int seconds) async {
await Future.delayed(Duration(seconds: seconds));
return dish;
}
Future<void> main() async {
final stopwatch = Stopwatch()..start();
String soup = await cook('Soup', 2);
String salad = await cook('Salad', 1);
print('$soup and $salad');
print('Time: ${stopwatch.elapsed.inSeconds} seconds');
}
Try it Yourself »
Result:
Soup and Salad
Time: 3 seconds
This took 3 seconds, because the salad was only started after the soup was done.
At the Same Time
If the tasks do not depend on each other, you can start them all first, and then wait for all of them.
This is called running tasks concurrently.
Use await Future.wait() with a list of futures:
Example
Future<String> cook(String dish, int seconds) async {
await Future.delayed(Duration(seconds: seconds));
return dish;
}
Future<void> main() async {
final stopwatch = Stopwatch()..start();
List<String> dishes = await Future.wait([cook('Soup', 2), cook('Salad', 1)]);
print(dishes);
print('Time: ${stopwatch.elapsed.inSeconds} seconds');
}
Try it Yourself »
Result:
[Soup, Salad]
Time: 2 seconds
Now it took only 2 seconds, because both dishes were cooking at the same time.
You can also put the futures in a record and use .wait.
This works even when the futures have different types, and you can unpack the results with a pattern:
Example
Future<String> getName() async {
await Future.delayed(Duration(seconds: 1));
return 'Emma';
}
Future<int> getAge() async {
await Future.delayed(Duration(seconds: 1));
return 28;
}
Future<void> main() async {
final (name, age) = await (getName(), getAge()).wait;
print('$name is $age years old');
}
Try it Yourself »
Result:
Emma is 28 years old
Tip: Use await one after another only when a task needs the result of the task before it.
Otherwise, start the tasks together to save time.