Why Async?
Some tasks take time: loading data from the internet, reading a file, waiting for the database. If your app waits on the main thread, the screen freezes. Asynchronous code says: start this task, continue with other work, and come back when the result is ready.
Simple example: You order pizza by phone (start the task). You do not stand at the door doing nothing. You watch TV and when the bell rings (the result is ready), you go and take it.
Future
A Future<T> is a promise of a value of type T that will arrive later.
dart
Future<String> fetchName() {
return Future.delayed(const Duration(seconds: 2), () => 'Asha');
}
void main() {
print('Start');
fetchName().then((name) => print('Got $name'));
print('End');
}
// Start, End, then (after 2 seconds) Got Asha
async and await
await is an easier way to use a Future. It makes asynchronous code look like normal code. A function that uses await must be marked async and returns a Future.
dart
Future<void> main() async {
print('Start');
String name = await fetchName();
print('Got $name');
print('End');
}
// Start, Got Asha, End
Error Handling
dart
Future<int> loadAge() async {
await Future.delayed(const Duration(seconds: 1));
throw Exception('Server not reachable');
}
Future<void> main() async {
try {
int age = await loadAge();
print(age);
} catch (e) {
print('Error: $e');
} finally {
print('Done');
}
}
Running Futures Together
dart
Future<void> main() async {
// One after another: takes 4 seconds
var a = await slowTask(2);
var b = await slowTask(2);
// Together: takes about 2 seconds
var results = await Future.wait([slowTask(2), slowTask(2)]);
print(results);
}
Future<int> slowTask(int s) async {
await Future.delayed(Duration(seconds: s));
return s;
}
Stream
A Future gives one value later. A Stream gives many values over time, such as chat messages, location updates or a countdown.
dart
Stream<int> countdown() async* {
for (int i = 3; i > 0; i--) {
await Future.delayed(const Duration(seconds: 1));
yield i; // send a value into the stream
}
}
Future<void> main() async {
await for (final n in countdown()) {
print(n);
}
print('Liftoff!');
}
dart
import 'dart:async';
final controller = StreamController<String>();
controller.stream.listen((msg) => print('Received $msg'));
controller.add('Hello');
controller.add('World');
controller.close();
| Future | Stream |
| Values | One | Many |
| Get them with | await | await for or listen |
| Flutter widget | FutureBuilder | StreamBuilder |
| Example | Fetch a profile | Chat messages |
Flutter rule: Never block the UI. Always use await for network, file and database work. You will use FutureBuilder and StreamBuilder in later lessons.
Conclusion
Async code keeps your app smooth. Use Future with async and await for one result, and Stream for a flow of results.
Quick Summary: Future is one value later and Stream is many. Use async and await with try and catch.