Flutter websocket disconnect listening Flutter websocket disconnect listening dart dart

Flutter websocket disconnect listening


You can find out if websocket is closed by implementing onDone callback. See the example below:

      _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');        },      );

Hope that helps.


Other answers around SO and the web suggest that you can't just keep sockets open in the background (which seems reasonable, you'd be keeping open network connections that may affect battery life). Depending on your use case, you might be better looking at Push Notifications or something that checks on a schedule.