We have a Flutter application that uses websockets for server initiated communication. We use flutter_bloc as the state management mechanism across the app. UI events are conveyed to the widget through Bloc state transitions and BlocBuilder widgets.
An additional requirement is, there are some widgets should be re-rendered based on specific events received from the server over websocket.
StreamBuilder is a natural way to react to events received on the websocket. But was not sure about the best way to incorporate it in uI widgets that using Blocs.
Would appreciate inputs from the community on structuring code cleanly when Bloc and websocket channels are to be used together.
Solution 1: krns
You can use the BlocBuilder:
- Listen in your bloc for websocket messages and add new bloc event
- The bloc event holds the websocket message
mapEventToStateyour event is mapped to a new bloc state which contains the message content
Talking about the official todo example:
- You get a websocket message that a new todo was added
- You add a new bloc event
mapEventToStateadd the todo to the list of todos and yield a new state
- Because of the BlocBuilder the UI should rebuild automatically