How to handle websocket with dart:io Flutter

Viewed 223

I would like to avoid using the package web_socket_channel which despite its vote doesn't seem to not be actively maintained (many github issues not answered) and doesn't handle errors.

I simply need to connect from Flutter to my WebSocket API in AWS.

How can i do that with dart:io package ? Or is it possible with socket_io_client ? I see that the connection is with http and not wss.

1 Answers

I have found a way in addition to the usual try - catch to handle error in the channel.sink.listen StreamSubscription object with the web_socket_channel package.

You can do the following according to this answer :

 _channel = IOWebSocketChannel.connect(
        'ws://yourserver.com:port',
      );

      ///
      /// Start listening to new notifications / messages
      ///
      _channel.stream.listen(
        (dynamic message) {
          debugPrint('message $message');
        },
        onDone: () {
          debugPrint('ws channel closed');
        },
        onError: (error) {
          debugPrint('ws error $error');
        },
      );

This actually works and there is no need to use SocketIO in my use case of course.

Related