TechnicalMedium Flutter
What is the difference between a Future and a Stream in Dart?
Asked for Mobile Developer
Why they ask this: Networking, databases and real-time features in Flutter depend on async Dart.
Answer
- A
Future<T>delivers one value (or an error) later, such as an HTTP response. Use it withasync/awaitorFutureBuilder. - A
Stream<T>delivers many values over time, such as location updates, Firestore snapshots, WebSocket messages or user input. Use it withawait for,listen()orStreamBuilder.
text
Future<List<Job>> fetchJobs() async {
final res = await http.get(Uri.parse('https://api.example.com/jobs'));
if (res.statusCode != 200) throw Exception('Failed: ${res.statusCode}');
return (jsonDecode(res.body) as List).map((j) => Job.fromJson(j)).toList();
}
Stream<int> countdown(int from) async* {
for (var i = from; i >= 0; i--) {
await Future.delayed(const Duration(seconds: 1));
yield i;
}
}Always cancel stream subscriptions in dispose() to avoid memory leaks.
Can you explain this in your own words?