Search code examples
flutterwebsocketbloc

Design recommendations for using flutter bloc library and websockets together


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

  • You can use the BlocBuilder:

    • Listen in your bloc for websocket messages and add new bloc event
    • The bloc event holds the websocket message
    • In mapEventToState your 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 TodoAdded(message)
    • In mapEventToState add the todo to the list of todos and yield a new state TodosLoadSuccess(todos)
    • Because of the BlocBuilder the UI should rebuild automatically