How to make flutter wait on a WebSocket response

Viewed 17

I'm syncing my project up with my website, and the first thing I want to do is to have it ping the server to make sure it can connect.

var responses= [];

@override
Widget build(BuildContext context){
var ws = WebSocketChannel.connect(Uri.parse("[NAME]"));
ws.stream.listen((data))=>responses.add(data));
ws.sink.add("[CONNECT_PACKET]");
}

If the packet comes back fine, I want the webpage to display as normally. Otherwise, I want it to display an "error: servers down" page. How can I have the program wait for the packet to come through? I found some answers that involved a FutureBuilder, but I don't know how I can get WebSocket to add a Future to responses, then update that when the packet comes in. (Still fairly new to flutter)

Thanks!

1 Answers

You can use StreamBuilder to subscribe to the stream

return StreamBuilder<bool>(
  stream: ws.stream,
  initialData: false,
  builder:(BuildContext context, AsyncSnapshot<bool> snapshot) {
    final hasConnection = snapshot.hasData && snapshot.data!;
    if (hasConnection) {
      // return success widget
    } else {
      // return network error widget
    }
  },
);
Related