For this recipe, we will use a StreamSubscription with its methods. We will also add a button to close the stream. Perform the following steps:
- At the top of the _StreamHomePageState class, declare a StreamSubscription called subscription:
StreamSubscription subscription;
- In the initState method of the _StreamHomePageState class, remove StreamTransformer and set the subscription. The final result is shown here:
@override
void initState() {
numberStream = NumberStream();
numberStreamController = numberStream.controller;
Stream stream = numberStreamController.stream;
subscription = stream.listen((event) {
setState(() {
lastNumber = event;
});
});
super.initState();
}
- Still in the initState method, after setting subscription, set the optional onError property of subscription:
subscription.onError((error) {
setState(() {
lastNumber = -1;
});
});
- After the onError property, set the onDone property...