Dart: Streams

Utsav Ghimire
2 min readDec 16, 2022
https://www.oreilly.com/library/view/scala-reactive-programming/9781787288645/066ac13d-279d-4767-869d-7b24a3e62913.xhtml

What is a stream?

A stream is a sequence of asynchronous events in the Dart programming language. Streams represent data produced over time, such as user input, network requests, or file I/O operations.

Streams are an essential part of the Dart ecosystem and are used extensively in the Flutter framework for building cross-platform mobile apps.

Basics of Streams:

You can use the Stream class or one of its subclasses to create a stream in Dart. For example, you can create a stream of integers like this:

Stream<int> stream = Stream.fromIterable([1, 2, 3]);

You can also create a stream that generates events on demand using the Stream.generate method:

Stream<int> stream = Stream.generate(() => 1);

To listen for events on a stream, you can use the listen method. This method takes a callback function that will be called for each event emitted by the stream.

Here’s an example of how you might listen for events on a stream:

stream.listen((event) {
print(event);
});

Streams can also be transformed and combined using various operators. For example, you can use the map operator to transform the events emitted by a stream:

Stream<int> stream = Stream.fromIterable([1, 2, 3]);
Stream<String> mappedStream = stream.map((event) => 'Number: $event');
mappedStream.listen((event) {
print(event);
});

The above code will print “Number: 1”, “Number: 2”, and “Number: 3” to the console.

You can also use the where operator to filter the events emitted by a stream:

Stream<int> stream = Stream.fromIterable([1, 2, 3, 4, 5]);
Stream<int> filteredStream = stream.where((event) => event % 2 == 0);
filteredStream.listen((event) {
print(event);
});

The above code will print “2” and “4” to the console.

Error Handling:

Streams can also emit errors, and it is essential to handle them properly to prevent your application from crashing. To handle errors on a stream, you can use the catchError operator.

Here’s an example of how you might use catchError to handle errors on a stream:

Stream<int> stream = Stream.fromIterable([1, 2, 3]);
stream = stream.map((event) {
if (event == 2) {
throw Exception('Error');
}
return event;
});
stream.listen((event) {
print(event);
}, onError: (error) {
print(error);
});

The above code will print “1” and “Error” to the console.

Conclusion:

This article covered the basics of streams in Dart, including how to create and listen for events on a stream, transform and combine streams, and handle errors on a stream. Streams are an essential part of the Dart ecosystem and are used extensively in the Flutter framework for building mobile apps.

--

--