Multiple StreamBuilder using same data source

Directly connecting to websocket using Streambuilder works seamlessly but I tried to make the stream part of the provider so that I can access the stream data in multiple widgets without encountering the "Bad State: Stream has already been listened to".

Is this a best way of handling multistreaming of data, if not what are my options?

Websocket server is part of Django

Code for provider is mentioned below

  late final WebSocketChannel _fpdSockets;

  Map _webSocketMessages = {};

  Map get webSocketMessages {
    return _webSocketMessages;
  }


  WebSocketStreamProvider()
      : _fpdSockets = IOWebSocketChannel.connect(
          Uri.parse('ws://127.0.0.1:8000/ws/socket-server/'),
        );

  Stream<Map<String, dynamic>> get dataStream => _fpdSockets.stream
      .asBroadcastStream()
      .map<Map<String, dynamic>>((value) => (jsonDecode(value)));

  void sendDataToServer(dataToServer) {
    print("Sending Data");
    _fpdSockets.sink.add(
      jsonEncode(dataToServer),
    );
  }

  void closeConnection() {
    _fpdSockets.sink.close();
  }

  handleMessages(data) {
    print(data);
    _webSocketMessages = data;
    // notifyListeners();
  }
}

Back to Top