Instead of using an asynchronous for loop, you can also leverage the listen method over a stream. To do that, perform the following steps:
- Remove or comment out the content of the changeColor method.
- Add the following code to the changeColor method:
colorStream.getColors().listen((eventColor) {
setState(() {
bgColor = eventColor;
});
});
- Run the app. You'll notice that our app behaves just like before, changing the color of the screen each second.
The main difference between listen and await for is that when there is some code after the loop, listen will allow the execution to continue, while await for stops the execution until the stream is completed.
In this particular app, we never stop listening to the stream, but you should always close a stream when it has completed its tasks. In order to do that, you can use the close() method, as shown in the next recipe.