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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With