Junior — Middle
What is the difference between Stream and Future objects in the context of asynchronous programming?
sobes.tech AI
Answer from AI
In the context of asynchronous programming in Flutter (Dart), objects Future and Stream are used for working with asynchronous operations but serve different purposes:
-
Future represents the result of an asynchronous operation that will complete once in the future. It's like a promise to get a value or an error.
-
Stream represents a sequence of asynchronous events or data that can arrive multiple times over time.
Example:
// Future: getting a single value
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2));
return 'Data loaded';
}
// Stream: getting multiple values over time
Stream<int> countStream() async* {
for (int i = 1; i <= 5; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}
In summary, Future is for a single asynchronous operation with one result, Stream is for a sequence of asynchronous events.