Back to results for “Error Handling”
Flutter › Dart Asynchronous Programming (Future & async/await)

How do the async and await keywords let you write asynchronous code in Dart that reads and looks like simple, straightforward sequential code?

Beginner

Answer

Marking a function with the async keyword allows you to use the await keyword within that function's body, which pauses that specific function's execution at that exact point until the awaited Future actually completes, then resumes execution with the Future's resulting value, and this lets you write asynchronous code that reads in a natural, straightforward top to bottom sequential style, rather than needing to nest multiple separate then callback functions together, which can otherwise quickly become difficult to read for anything beyond a very simple asynchronous operation.
Future<void> loadUserData() async {
  final user = await fetchUser();
  final orders = await fetchOrders(user.id);
  print('Loaded ${orders.length} orders');
}
Real-world example A checkout screen uses async and await to first fetch the current user's profile and then fetch that same user's order history, with each step clearly and sequentially readable, rather than being nested inside several separate confusing callback functions.

Common follow-ups: Can you use await outside of a function explicitly marked as async?;What happens to the rest of an async function's code after it hits an await statement?