Alex Wright
Alex Wright

Reputation: 627

"Socket id" is null while a connection is established in Flutter

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.

Upvotes: 1

Views: 540

Answers (1)

Rohan Jariwala
Rohan Jariwala

Reputation: 2050

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));
    }

Upvotes: 1

Related Questions