Day 15: Async Programming Deep Dive
Fetching data, listening to updates, and keeping your UI responsive. Today, we master the core of modern apps: asynchronous programming with Futures and Streams.
The Promise: Understanding `Future`
A `Future` is exactly what it sounds like: a promise to give you a value at some point in the future. Think of ordering food at a restaurant. You get a receipt (a `Future`), and you wait. Eventually, your order (the value) is ready. The keywords `async` and `await` are how we handle this waiting process elegantly.
Live Simulation:
Click the button to fetch user data.
The Code:
// 1. The function is marked 'async' to use 'await'.
Future<String> fetchUserData() async {
// 2. 'await' pauses here, but DOES NOT block the UI.
await Future.delayed(Duration(seconds: 2));
// 3. After 2 seconds, this value is returned.
return 'Hello, Alex! ๐';
}
void onButtonPressed() async {
// Show loading spinner...
final userData = await fetchUserData();
// Display userData, hide spinner.
}
The River: Mastering `Stream`
If a `Future` is a promise for one value, a `Stream` is like a river that delivers multiple values over time. Think of a news feed, notifications, or a countdown timer. You “listen” to the stream and react every time a new piece of data comes down the river.
Live Simulation:
The Code:
// 1. 'async*' marks a function that returns a Stream.
Stream<int> countdown() async* {
for (int i = 5; i > 0; i--) {
// 2. Wait for 1 second.
await Future.delayed(Duration(seconds: 1));
// 3. 'yield' sends a value into the stream.
yield i;
}
}
void listenToStream() {
countdown().listen((number) {
// This code runs every time a number is yielded.
print(number);
});
}
The Builders: `FutureBuilder` & `StreamBuilder`
So how do we connect these async operations to our UI? Flutter provides two incredibly useful widgets: `FutureBuilder` and `StreamBuilder`. They listen to a `Future` or `Stream` and automatically rebuild your UI with the correct state: loading, error, or data.
FutureBuilder Simulation
Idle
StreamBuilder Simulation
Idle