I'm building a chat feature using Flutter frontend, Node.js backend, MongoDB, and Socket.IO.
Issue:
When sending the first message in a conversation, the message appears twice (duplicated).
If I exit to Message Screen and re-enter Chat Screen, everything works normally and no duplicates appear.
Facts:
• Socket.IO is enabled.
• Seed users do not join socket rooms (no realtime).
• Real user (Long Hoang) does connect via socket.
• Messages are correctly saved to MongoDB.
• Duplicate only happens on the first message.
Current suspicion:
1. Backend emits the message twice (once in controller, once in socket handler).
2. Flutter adds the message to state locally AND receives the same message back via socket.
3. ChatRoom may have multiple rooms for same pair of users in previous seed attempts.
Questions:
• Why does duplication occur only on first message?
• How to detect double emits from backend?
• How to ensure Flutter appends message only once?
• How to verify the real user is properly connected to the socket room?
• Best way to refactor controller + socket logic to avoid double emissions?