The `asStream` method in Dart creates a Stream containing the result of a Future.
The syntax of Future.asStream() method is:
Stream<T> asStream()
This asStream() method of Future creates a Stream containing the result of this future.
Future.asStream() returns value of type Stream<T>
.
In this example,
futureInt
with a value of 42.asStream()
.void main() {
Future<int> futureInt = Future.value(42);
Stream<int> streamInt = futureInt.asStream();
streamInt.listen((data) {
print('Received data from stream: $data');
});
}
Received data from stream: 42
In this example,
futureString
with the value 'Hello, Dart!'.asStream()
.void main() {
Future<String> futureString = Future.value('Hello, Dart!');
Stream<String> streamString = futureString.asStream();
streamString.listen((data) {
print('Received data from stream: $data');
});
}
Received data from stream: Hello, Dart!
In this example,
futureList
with a list of integers [1, 2, 3, 4, 5].asStream()
.void main() {
Future<List<int>> futureList = Future.value([1, 2, 3, 4, 5]);
Stream<List<int>> streamList = futureList.asStream();
streamList.listen((data) {
print('Received data from stream: $data');
});
}
Received data from stream: [1, 2, 3, 4, 5]
In this Dart tutorial, we learned about asStream() method of Future: the syntax and few working examples with output and detailed explanation for each example.