Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart async/await


Share

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.

  • async marks a function as asynchronous.
  • await waits 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:

Example

void main() {
  String food = await Future.value('Pizza');
  print(food);
}
Try it Yourself »

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.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.