Streams are a fundamental concept in Dart for handling asynchronous data. They provide a powerful way to work with sequences of events or data that arrive over time.
A stream in Dart is a sequence of asynchronous events. It's like a pipe through which data flows, allowing you to process information as it becomes available. Streams are particularly useful for:
Dart offers several ways to create streams. Here's a simple example using Stream.fromIterable()
:
Stream<int> numberStream = Stream.fromIterable([1, 2, 3, 4, 5]);
This creates a stream that emits integers from 1 to 5.
To consume data from a stream, you can use the listen()
method:
numberStream.listen((int number) {
print('Received: $number');
});
Streams can be transformed using various methods. The map()
function is commonly used for this purpose:
Stream<int> doubledStream = numberStream.map((number) => number * 2);
doubledStream.listen((int number) {
print('Doubled: $number');
});
Dart's async and await keywords work seamlessly with streams, making asynchronous programming more intuitive:
Future<void> processStream() async {
await for (var number in numberStream) {
print('Processing: $number');
}
}
Streams can also handle errors. You can catch errors using the onError
parameter of the listen()
method:
numberStream.listen(
(int number) { print('Received: $number'); },
onError: (error) { print('Error: $error'); },
onDone: () { print('Stream completed'); }
);
await for
loops for simple stream processing.Dart streams provide a powerful mechanism for handling asynchronous data. They're essential for building responsive applications, especially in scenarios involving real-time data or long-running operations. By mastering streams, you'll be able to write more efficient and scalable Dart code.
For more advanced stream operations, explore the Dart async library, which offers additional utilities for working with asynchronous programming in Dart.