On this page12 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. What Is a Future?
  4. 2. async and await
  5. 3. The Program Doesn't Stop and Wait
  6. 4. Errors: try / catch
  7. 5. Waiting for Several at Once
  8. Code Examples
  9. Common Beginner Mistakes
  10. Practice Questions
  11. Practice Answers
  12. Key Takeaways

Lecture 056: Future, async & await

DayExtra Topics
Lecture056 of 057
Estimated video length14 min
TargetDart 3.12
LevelBeginner

Loading a web page, reading a file, asking a server: these take time. Your app shouldn't freeze while it waits. A Future is a promise of a value that will arrive later, and async / await let you write waiting code that reads like normal step-by-step code.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lectures 025 (functions), 037 (exception handling) and 048 (anonymous functions).


Learning Objectives

  • Explain what a Future is
  • Write an async function that returns a Future
  • Wait for a result with await
  • Handle errors with try / catch
  • Know the older .then() style
  • Run several futures at once with Future.wait

1. What Is a Future?

A Future<String> is a box that will hold a String later. Here, Future.delayed pretends to be a slow server:

dart
Future<String> fetchUserName() {
  return Future.delayed(Duration(seconds: 1), () => 'Ayesha');
}

Calling it gives you the box straight away, not the name:

dart
var marks = fetchMarks();
print(marks);   // Instance of 'Future<int>'

2. async and await

Mark a function async, and inside it use await to wait for a future's value:

dart
Future<int> fetchMarks() async {
  await Future.delayed(Duration(milliseconds: 500));
  return 87;
}

Future<void> main() async {
  var name = await fetchUserName();
  print('Got name: $name');        // after 1 second

  var marks = await fetchMarks();
  print('Marks: $marks');          // after another 0.5 seconds
}

Three rules:

  1. await only works inside a function marked async.
  2. An async function always returns a Future. return 87; in a Future<int> function is fine; Dart wraps it.
  3. If main uses await, write it as Future<void> main() async.

3. The Program Doesn't Stop and Wait

Without await, the code carries on and the result arrives later:

dart
print('1. Start');
fetchUserName().then((name) => print('3. Got name with then: $name'));
print('2. This line does not wait');

Output

code
1. Start
2. This line does not wait
3. Got name with then: Ayesha

.then(...) is the older way to say "when it arrives, run this". You'll see it in existing code, but await is easier to read.

4. Errors: try / catch

A future can fail (no internet, server down). With await, catch errors exactly as in Lecture 037:

dart
Future<String> fetchFails() async {
  await Future.delayed(Duration(milliseconds: 200));
  throw Exception('Server not reachable');
}

try {
  await fetchFails();
} catch (e) {
  print('Caught: $e');   // Caught: Exception: Server not reachable
}

5. Waiting for Several at Once

await-ing one after another adds up the times (1 s + 0.5 s). Future.wait runs them together:

dart
var results = await Future.wait([fetchUserName(), fetchMarks()]);
print(results);   // [Ayesha, 87], after about 1 second, not 1.5

Code Examples

Example 1: Opening an App: Log In, Then Load Data

dart
Future<bool> checkLogin(String user, String password) async {
  print('Checking login for $user...');
  await Future.delayed(Duration(milliseconds: 800));
  return password == 'dart123';
}

Future<List<String>> loadCourses(String user) async {
  print('Loading courses...');
  await Future.delayed(Duration(milliseconds: 600));
  return ['Dart Basic', 'Flutter Widgets', 'Firebase'];
}

Future<void> openApp(String user, String password) async {
  try {
    var ok = await checkLogin(user, password);
    if (!ok) {
      throw Exception('Wrong password');
    }
    var courses = await loadCourses(user);
    print('Welcome, $user! Your courses:');
    for (var c in courses) {
      print(' - $c');
    }
  } catch (e) {
    print('Could not open the app: $e');
  } finally {
    print('Loading spinner hidden.');
  }
}

Future<void> main() async {
  await openApp('sara', 'dart123');
  print('');
  await openApp('sara', 'oops');
}

Output

code
Checking login for sara...
Loading courses...
Welcome, sara! Your courses:
 - Dart Basic
 - Flutter Widgets
 - Firebase
Loading spinner hidden.

Checking login for sara...
Could not open the app: Exception: Wrong password
Loading spinner hidden.

The steps read top to bottom like normal code, even though each one waits. finally runs whether login worked or not, which is the right place to hide a loading spinner.


Common Beginner Mistakes

1. Treating a Future as its value

dart
int marks = fetchMarks();
code
Error: A value of type 'Future<int>' can't be assigned to a variable of type 'int'.

Write int marks = await fetchMarks(); inside an async function.

2. await in a function that isn't async

dart
void main() {
  var marks = await fetchMarks();
}
code
Error: 'await' can only be used in 'async' or 'async*' methods.

Change it to Future<void> main() async { ... }.

3. Forgetting await: print(fetchMarks()); prints Instance of 'Future<int>', not 87.

4. Awaiting one by one when the jobs are independent: use Future.wait([...]) to run them together and save time.


Practice Questions

  1. What is a Future<String>?
  2. What two words do you need to wait for a future's value inside a function?
  3. What does an async function always return?
  4. What does print(fetchMarks()); print (without await)?
  5. How do you catch an error from an awaited future?
  6. Two independent requests take 2 s and 3 s. About how long does Future.wait take for both?

Practice Answers

  1. A promise of a String that will be available later.
  2. async on the function, await before the future.
  3. A Future.
  4. Instance of 'Future<int>'
  5. Wrap the await in try { ... } catch (e) { ... }.
  6. About 3 seconds: they run at the same time.

Key Takeaways

  • A Future<T> is a value of type T that arrives later.
  • Mark functions async; use await to get the value.
  • An async function returns a Future; write Future<void> main() async when main awaits.
  • Handle failures with try / catch / finally.
  • .then() is the older style; Future.wait runs futures together.