Flutter how to listen to websocket response?
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.
You need to manage this yourself in your state class.
final list = List<Message>();@overrideWidget build(BuildContext context) { return new StreamBuilder( stream: myStream, builder: (context, snapshot) { list.add(/* extract message from snapshot */); /* build a widget with your list */ }, );}
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?
Dart has two kinds of streams, single-subscription and broadcast streams. See more info about the differences, and how to create streams. Recommendations here will depend largely on your application.
That said, usually apis that return a stream default to single-subscription and then have the asBroadcastStream()
alternative.
If that's not an option, you can create an intermediate StreamController
that listens on your single-subscription stream and returns a broadcast stream, that the rest of your app should listen to.
Both of these options are outlined in the link above about creating streams.