StreamController also helps you when dealing with errors. To enable error handling, perform the following steps:
- In the stream.dart file, add a new method, called addError, with the following code:
addError() {
controller.sink.addError('error');
}
- In the main.dart file, append to the listen method in the initState function of _StreamHomePageState of the onError method, as shown here:
stream.listen((event) {
setState(() {
lastNumber = event;
});
}).onError((error) {
setState(() {
lastNumber = -1;
});
});
- Finally, in the addRandomNumber method, comment out the call to addNumberToSink and call addError on the numberStream instance instead:
void addRandomNumber() {
Random random = Random();
//int myNum = random.nextInt(10);
//numberStream.addNumberToSink(myNum);
numberStream.addError();
}
- Run the app and press the button. You should see a -1 in the center of the screen.
- Remove...