rikulo / socket.io-client-dart

socket.io-client-dart: Dartlang port of socket.io-client https://github.com/socketio/socket.io-client
https://quire.io
MIT License
675 stars 185 forks source link

Socket IO Client Event Firing Twice #352

Closed davie1989 closed 1 year ago

davie1989 commented 1 year ago

Hi. Thanks for this great library.

I am currently trying to build a chat with the library, but new messages causes the on event to fire twice. I have tried several approaches but none is working.

Below is a sample code.

late Socket socket;
var  _ctrl = Get.put(ChatsController()),

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

  _initSocket() {
    socket = io(
              ApiEndpointsConst.socketUrl,
              OptionBuilder()
                  .setTransports(["websocket"])
                  .setPath("/u/socket/socket.io")
                  .setQuery(<String, dynamic>{"token": username})
                  .setReconnectionAttempts(5)
                  .disableForceNewConnection()
                  .disableAutoConnect()
                  .build());
      socket.connect();
      socket.onConnect((_){
        socket.on('new/service/message', (data) => _onNewMsg(data));
    });
  }

  @override
  void dispose() {
      socket.dispose();
    super.dispose();
  }

  _onNewMsg(msg) {
    var payload = msg as List<dynamic>;
    var chat = jsonDecode(payload[3]);
    final newMsg = ChatWidget(
      ctrl: _ctrl,
      animationCtrl: AnimationController(
        duration: const Duration(milliseconds: 500),
        vsync: this,
      ),
      index: 0,
      chat: ChatsModdel.fromJson(chat),
    );
    _ctrl.chats.insert(0, newMsg);
    newMsg.animationCtrl.forward();
  }

Help will be appreciated. Thanks