โณ Lesson 3: Asynchronous Programming
The Problem: Why Async?
Imagine ordering coffee. Do you stare at the counter until it's ready, or do you check your phone while waiting?
โ Synchronous (Blocking)
โ Ordering...
โณ Waiting...
๐ฑ Can't use phone
โ Asynchronous (Non-blocking)
โ Ordering...
๐ฑ Check phone
๐ง Read emails
โ Coffee ready!
Today's Project: "Async Data Dashboard"
We'll build a dashboard that:
- ๐ Fetches data from multiple "APIs" concurrently
- ๐ Shows real-time progress indicators
- โก Handles slow networks gracefully
- ๐ก๏ธ Manages errors without crashing
- ๐ Displays performance metrics
Step 1
Future: The Promise of a Value
๐จ Future Lifecycle Visualizer
Uncompleted
Still working...
Completed with Value
Success! Here's your data
Completed with Error
Something went wrong
Click a stage to see it in action!
โ๏ธ Future Playground
๐ค Output
๐ Starting...
โณ Not waiting...
๐ฆ Data loaded!
โณ Not waiting...
๐ฆ Data loaded!
Step 2
Async/Await: Making Async Look Sync
๐ .then() vs async/await
๐ด Old Way: .then() Chains
fetchUser()
.then((user) => fetchPosts(user.id))
.then((posts) => fetchComments(posts[0].id))
.then((comments) => print(comments))
.catchError((e) => print('Error: $e'));
๐ฐ Callback hell!
VS
โจ New Way: async/await
try {
var user = await fetchUser();
var posts = await fetchPosts(user.id);
var comments = await fetchComments(posts[0].id);
print(comments);
} catch (e) {
print('Error: $e');
}
๐ Clean & readable!
๐ฎ Async/Await Simulator
2s
Start
Complete
Step 3
Concurrent Operations: Do More at Once
๐ Sequential vs Concurrent
Sequential (Slow)
Task 1
Task 2
Task 3
Total: 6 seconds
Concurrent (Fast)
Task 1
Task 2
Task 3
Total: 2 seconds
๐ง Live Editor: Future.wait()
// Fetch 3 APIs concurrently
final results = await Future.wait([
fetchUserData(),
fetchUserPosts(),
fetchUserFriends(),
]);
// All results ready at once!
print(results[0]); // User data
print(results[1]); // Posts
print(results[2]); // Friends
Step 4
Error Handling in Async Code
๐ก๏ธ Error Handling Playground
try {
var data = await fetchData();
print('โ
Success: $data');
} on TimeoutException catch (e) {
print('โฐ Timeout: $e');
} on FormatException catch (e) {
print('๐ Bad format: $e');
} catch (e) {
print('โ Unknown error: $e');
} finally {
print('๐งน Cleanup complete');
}
Select an error type to see handling
Step 5
Performance: Measuring Async Operations
๐ Async Performance Monitor
โฑ Sequential Time:
--s
โก Concurrent Time:
--s
๐ Speed Improvement:
--x
๐
Build: Async Data Dashboard
๐ Dashboard Requirements
๐งฉ Interactive Code Builder
Future<Map> fetchUserProfile() async {
await Future.delayed(Duration(seconds: 1));
return {'name': 'User', 'age': 25};
final results = await Future.wait([...]);
๐ฆ Drag code snippets here to build your async app
๐ฎ Async Challenge: Quick Quiz
๐ Score: 0/5
โก Streak: 0
โฑ Time: 0s
๐ก Hints: 3