How to make websocket stream broadcast to many other pages?
You can use broadcasts.
//Here is the solution StreamController<String> streamController = new StreamController.broadcast(); //Add .broadcast here//Now you can listen from various places@overridevoid initState() { super.initState(); print("Creating a StreamController..."); //First subscription streamController.stream.listen((data) { print("DataReceived1: " + data); }, onDone: () { print("Task Done1"); }, onError: (error) { print("Some Error1"); }); //Second subscription streamController.stream.listen((data) { print("DataReceived2: " + data); }, onDone: () { print("Task Done2"); }, onError: (error) { print("Some Error2"); }); streamController.add("This a test data"); print("code controller is here");}
Font: https://medium.com/@ayushpguptaapg/using-streams-in-flutter-62fed41662e4
When using broadcasts you can have multiple listeners in the same stream.
If you simply use a stream without ".broadcast ()" you can only have one listener
Solution for package web_socket_channel:
final channel = IOWebSocketChannel.connect(socketUrl);final streamController = StreamController.broadcast();streamController.addStream(channel.stream);
After that simply use streamController.stream
to listen web socket events.
As there are no useful answer, I update my answer here for other reference.
- duplicate subscribe stream is a desired behaviour in flutter.
if you are just using a StreamBuilder, the stream can be listen only once. think about it, if your stream can be listen to many other pages or widgets, then data would be repeated.
- But if you want using one single stream, and update all widgets
this is really can be occured when develop a complicated app, for example, you are building a chat app, new message comes, you should update many pages UI (your dialog chat ui, your session list ui....), then you should subscribe this streams in many pages, I still not found a proper way to do this, except make this stream to be broadcast, and do your work.