On this page12 sections
Lecture 056: Future, async & await
| Day | Extra Topics |
| Lecture | 056 of 057 |
| Estimated video length | 14 min |
| Target | Dart 3.12 |
| Level | Beginner |
Loading a web page, reading a file, asking a server: these take time. Your app shouldn't freeze while it waits. A
Futureis a promise of a value that will arrive later, andasync/awaitlet 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
Futureis - Write an
asyncfunction that returns aFuture - 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:
Future<String> fetchUserName() {
return Future.delayed(Duration(seconds: 1), () => 'Ayesha');
}Calling it gives you the box straight away, not the name:
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:
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:
awaitonly works inside a function markedasync.- An
asyncfunction always returns aFuture.return 87;in aFuture<int>function is fine; Dart wraps it. - If
mainusesawait, write it asFuture<void> main() async.
3. The Program Doesn't Stop and Wait
Without await, the code carries on and the result arrives later:
print('1. Start');
fetchUserName().then((name) => print('3. Got name with then: $name'));
print('2. This line does not wait');Output
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:
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:
var results = await Future.wait([fetchUserName(), fetchMarks()]);
print(results); // [Ayesha, 87], after about 1 second, not 1.5Code Examples
Example 1: Opening an App: Log In, Then Load Data
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
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
int marks = fetchMarks();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
void main() {
var marks = await fetchMarks();
}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
- What is a
Future<String>? - What two words do you need to wait for a future's value inside a function?
- What does an
asyncfunction always return? - What does
print(fetchMarks());print (withoutawait)? - How do you catch an error from an awaited future?
- Two independent requests take 2 s and 3 s. About how long does
Future.waittake for both?
Practice Answers
- A promise of a
Stringthat will be available later. asyncon the function,awaitbefore the future.- A
Future. Instance of 'Future<int>'- Wrap the
awaitintry { ... } catch (e) { ... }. - About 3 seconds: they run at the same time.
Key Takeaways
- A
Future<T>is a value of typeTthat arrives later. - Mark functions
async; useawaitto get the value. - An
asyncfunction returns aFuture; writeFuture<void> main() asyncwhenmainawaits. - Handle failures with
try/catch/finally. .then()is the older style;Future.waitruns futures together.