Design recommendations for using flutter bloc library and websockets together
Asked Answered
R

2

7

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.

Rothstein answered 22/2, 2020 at 7:36 Comment(0)
S
3

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
Snivel answered 25/6, 2020 at 14:49 Comment(1)
Where should the socket code be placed? I think you should be more clear about the answer. I have tried putting socket codr inside the costuctor's body. But it is not working.Fiedler
K
0

I put the code in the bloc itself, you just need to declare the websocketchannel in init state of the widget and then pass the channel to bloc and listen to events in there

Kickshaw answered 18/1, 2023 at 7:31 Comment(2)
And don't forget to dispose the sink in the dispose method of the stateful widget, like this: _channel.sink.close();Kickshaw
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Preterite

© 2022 - 2024 — McMap. All rights reserved.