Why Asynchronous Code Exists
Understanding Future
Future<String> fetchUsername() {
return Future.delayed(Duration(seconds: 2), () => "Ahmed");
}
void main() {
fetchUsername().then((name) {
print("Hello, $name");
});
print("Fetching username...");
}Future States
Flashcards
What is a Future in Dart?
Hint: Think of it as an IOU for a value.
Tap to flipAn object representing a value or error that will be available at some point in the future, rather than immediately.
The async and await Keywords
Future<void> printUsername() async {
print("Fetching username...");
String name = await fetchUsername();
print("Hello, $name");
}Rules for async Functions
Future<int> getAge() async {
return 25; // Automatically becomes Future<int>
}Flashcards
What does 'await' actually pause?
Tap to flipIt pauses execution of the current async function only, not the entire app or event loop.
Error Handling with try/catch
Future<void> loadData() async {
try {
final data = await fetchDataFromApi();
print("Data: $data");
} catch (e) {
print("Failed to load data: $e");
} finally {
print("Request finished");
}
}Running Futures Concurrently
Future<void> loadDashboard() async {
final results = await Future.wait([
fetchUserProfile(),
fetchNotifications(),
fetchSettings(),
]);
final profile = results[0];
final notifications = results[1];
final settings = results[2];
}Flashcards
When should you use Future.wait() instead of sequential awaits?
Tap to flipWhen the async operations are independent of each other and you just need all their results before continuing.
Async/Await in Flutter Widgets
class ProfileScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: fetchUsername(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text("Error: ${snapshot.error}");
}
return Text("Hello, ${snapshot.data}");
},
);
}
}Avoiding setState After Dispose
Future<void> loadProfile() async {
final data = await fetchUserProfile();
if (!mounted) return;
setState(() {
_profile = data;
});
}Flashcards
Why check 'mounted' before setState in an async function?
Hint: The widget may be gone by the time await returns.
Tap to flipTo avoid calling setState on a State object whose widget has already been disposed, which throws a runtime error.
Final review
Test what you learned across the whole post.
Which statement about await is correct?
Flashcards
async + await, in one sentence
Tap to flipasync marks a function as returning a Future and enables await inside it; await pauses that function until a given Future resolves, without blocking the rest of the app.
