Dart Stream Methods
Stream methods collect the values of a whole stream into a single result. Each method returns a future, and await gives the finished result.
Summing a stream with fold
The fold call starts at 0 and adds each number in turn. The finished total is 15.
import 'dart:async';
Future<void> main() async {
var total = await Stream.fromIterable([1, 2, 3, 4, 5]).fold(0, (sum, n) => sum + n);
print(total);
}Collecting values with toList
The toList call waits for the stream to finish and collects its values. The list prints in stream order, and its length is 3.
import 'dart:async';
Future<void> main() async {
var values = await Stream.fromIterable([7, 8, 9]).toList();
print(values);
print(values.length);
}Finding a value with firstWhere
The first search finds 15 because it is the first value above ten. The second search finds nothing above ten, so orElse supplies -1.
import 'dart:async';
Future<void> main() async {
var found = await Stream.fromIterable([5, 15, 25]).firstWhere((n) => n > 10, orElse: () => -1);
var missing = await Stream.fromIterable([1, 2]).firstWhere((n) => n > 10, orElse: () => -1);
print(found);
print(missing);
}Counting values and testing for empty
The length read counts the three values of the first stream. The isEmpty read on an empty stream gives true.
import 'dart:async';
Future<void> main() async {
print(await Stream.fromIterable([2, 4, 6]).length);
print(await Stream<int>.empty().isEmpty);
}Example
import 'dart:async';
Future<void> main() async {
var total = await Stream.fromIterable([10, 20, 30, 40]).fold(0, (sum, n) => sum + n);
var count = await Stream.fromIterable([10, 20, 30, 40]).length;
print(total);
print(count);
print(total ~/ count);
}Key points
- Stream methods read a whole stream and return a future for one finished result.
- The fold method starts from an initial value and combines it with each value in turn.
- The toList method collects every value into a list in stream order.
- The firstWhere method returns the first value that passes its test.
- The orElse function of firstWhere supplies a fallback value for the case where nothing matches.
- The length property counts the values of a stream and gives the count as a future.
- The isEmpty property reports whether a stream holds no values, and it also gives its answer as a future.
In this example, fold adds the four values into a total of 100. A fresh stream then gives a count of 4 through length. The last print divides the total by the count with integer division and shows the average score 25.
Note
Each method consumes the stream it runs on, so a fresh stream is built for each method call in the example below.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What does the fold call give for the stream of 1, 2, 3 when it starts at 0 and adds each value?