In Dart, Future and Stream are fundamental classes used for asynchronous programming. They represent values or sequences of values that are computed asynchronously over time. Let's explore the purpose of these classes and provide examples along with their outputs.
Future Class:
A Future represents a single value or error that will be available at some point in the future. It is commonly used to represent the result of asynchronous operations, such as network requests or file I/O. You can use await to wait for a Future to complete and retrieve its value.
Example of Future:
Future<int> fetchValue() async {
await Future.delayed(Duration(seconds: 2)); // Simulate a 2-second delay.
return 42;
}
void main() async {
print('Fetching value...');
final result = await fetchValue();
print('Result: $result');
}
In this example, fetchValue returns a Future that represents the value 42 after a 2-second delay. When await is used in main, it pauses execution until the Future is resolved. The output will be:
Fetching value...
Result: 42
Stream Class:
A Stream represents a sequence of asynchronous events over time. It is often used for handling continuous data, such as user input, sensor data, or data from network sockets. You can listen to a Stream and react to events as they occur.
Example of Stream:
import 'dart:async';
Stream<int> countStream() {
return Stream.periodic(Duration(seconds: 1), (i) => i).take(5);
}
void main() {
final stream = countStream();
stream.listen((data) {
print('Received: $data');
}, onDone: () {
print('Stream is done.');
});
}
In this example, countStream returns a Stream that emits integers every second, and we take the first 5 values. The listen method is used to listen to the stream's events. The output will be:
Received: 0
Received: 1
Received: 2
Received: 3
Received: 4
Stream is done.
Here, the Stream emits values every second, and the listen callback prints each received value. When the stream is done, the onDone callback is executed.
Top comments (0)