Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter how to listen to websocket response?

As we all know, flutter has an example of using websocket, but it just receive websocket response as stream, and just something like this:

new StreamBuilder(
  stream: widget.channel.stream,
  builder: (context, snapshot) {
    return new Text(snapshot.hasData ? '${snapshot.data}' : '');
  },
);

What I am want is an async function which receives every websocket response and append the result to a list, so that the listview can be updated.

How to get the websocket response as text or json anyway?

Update: I know there are some method like stream.listen now:

widget.channel.stream.listen((data) {
  print("!!!!new msg: $data");
  var dataJson = json.decode(data);
  print(dataJson["content"]);
  // do something after received data
  setState(() {
    _allAnimateMessages.insert(0, newMsg);
  });
  newMsg.animationController.forward();
});

This can work in a page, but when enter that page again, there was an error says Bad state: Stream has already been listened to.. How to make the stream can be listened at every begaining, and then boradcast to many pages?

like image 754
Nicholas Jela Avatar asked May 23 '18 03:05

Nicholas Jela


1 Answers

Make sure you are closing your WebSocket connection when you leave the current widget. Inside your widget's State class you should have a dispose() method that looks like this:

@override
void dispose() {
  widget.channel.sink.close();
  super.dispose();
}
like image 62
JoeCherry Avatar answered Nov 10 '22 12:11

JoeCherry