Dart Future asStream()
Syntax & Examples
Future.asStream() method
The `asStream` method in Dart creates a Stream containing the result of a Future.
Syntax of Future.asStream()
The syntax of Future.asStream() method is:
Stream<T> asStream() This asStream() method of Future creates a Stream containing the result of this future.
Return Type
Future.asStream() returns value of type Stream<T>.
✐ Examples
1 Creating a stream from a Future
In this example,
- We create a Future
called futureIntwith a value of 42. - We convert this future into a Stream
using asStream(). - We listen to the stream and print received data.
Dart Program
void main() {
Future<int> futureInt = Future.value(42);
Stream<int> streamInt = futureInt.asStream();
streamInt.listen((data) {
print('Received data from stream: $data');
});
}Output
Received data from stream: 42
2 Creating a stream from a Future
In this example,
- We create a Future
called futureStringwith the value 'Hello, Dart!'. - We convert this future into a Stream
using asStream(). - We listen to the stream and print received data.
Dart Program
void main() {
Future<String> futureString = Future.value('Hello, Dart!');
Stream<String> streamString = futureString.asStream();
streamString.listen((data) {
print('Received data from stream: $data');
});
}Output
Received data from stream: Hello, Dart!
3 Creating a stream from a Future>
In this example,
- We create a Future
- > called
futureListwith a list of integers [1, 2, 3, 4, 5]. - We convert this future into a Stream
- > using
asStream(). - We listen to the stream and print received data.
Dart Program
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');
});
}Output
Received data from stream: [1, 2, 3, 4, 5]
Summary
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.