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
676 stars 186 forks source link

Hot Reload Causes Multiple SocketIO Client Instances In Flutter Web #374

Open YawarOsman opened 8 months ago

YawarOsman commented 8 months ago

I am encountering an issue in my Flutter web application where redundant event listeners are created every time the page is refreshed. I am using the socket.io package for Flutter to manage WebSocket connections, and it seems that a new listener for the event 'categoryUpdated' is registered every time the page is refreshed. This leads to multiple event handlers being invoked when the event is emitted, resulting in unexpected behavior.

Steps to Reproduce:

Navigate to a page in the Flutter web application.
Refresh the page multiple times.
Observe the console output or behavior of the application.

Expected Behavior:

Listeners for socket events should be registered only once and should persist across page refreshes. Subsequent refreshes should not result in the creation of additional listeners.

Actual Behavior:

Redundant listeners are created on each page refresh, leading to multiple invocations of event handlers when the event is emitted.

Additional Information:

Flutter version: 3.19.2
socket.io client package version: socket_io_client: ^2.0.3+1

Code Snippet:

import 'package:flutter/material.dart';
import 'package:socket_io_client/socket_io_client.dart' as io;

class SocketTestWidget extends StatefulWidget {
  const SocketTestWidget({super.key});

  @override
  State<SocketTestWidget> createState() => _SocketTestWidgetState();
}

class _SocketTestWidgetState extends State<SocketTestWidget> {
  late io.Socket socket;

  @override
  void initState() {
    super.initState();
    socket = io.io('http://localhost:3000', <String, dynamic>{
      'transports': ['websocket'],
      'autoConnect': false,
    });

    socket.connect();
    socket.on('categoryUpdated', (data) {
      print('aaaaaaaaa: $data');
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
bacotich commented 2 months ago

Hi, did you manage to solve the problem?

YawarOsman commented 2 months ago

Hi, the problem itself has not fixed yet, but there a way to get rid of it, is that to refresh the page with browser's reload button not flutter's hot reload or hot restart

bacotich commented 2 months ago

Hi, the problem itself has not fixed yet, but there a way to get rid of it, is that to refresh the page with browser's reload button not flutter's hot reload or hot restart

Thanks for the response, I'll try it that way.