Home > database >  "Socket id" is null while a connection is established in Flutter
"Socket id" is null while a connection is established in Flutter

Time:12-03

I use the following code to establish a connection with socket.io:

  late IO.Socket _socket;

@override
  void initState() {
    super.initState();

    _socket = IO.io('http://192.168.1.3:3001',
        IO.OptionBuilder().setTransports(['websocket']).build());

    print(_socket.id);
  }

When I run the app, _socket.id is null.

CodePudding user response:

You forgot to connect the socket like below

_socket.connect();

But the Way you're writing your code is not good. You can follow below pattern.

IO.Socket socket;
@override
void initState() {
  initSocket();
  super.initState();
}
initSocket() {
  socket = IO.io('http://192.168.1.3:3001', IO.OptionBuilder().setTransports(['websocket'])
.disableAutoConnect() .build());
      socket.connect();
      socket.onConnect((_) {
        print('Connection established');
      });
      socket.onDisconnect((_) => print('Connection Disconnection'));
      socket.onConnectError((err) => print(err));
      socket.onError((err) => print(err));
    }
  • Related