0

So, When I open the tab for the first time, data from Socket.IO appears. But when I change the tab and go back, I can't get data from Socket.IO.

This is my Code:

Map <String,dynamic> list;

IO.Socket socket = IO.io('http://localhost:3000', <String, dynamic>{
    'transports': ['websocket'] 
});

@override
initState(){
socket.on('connect',(_){
      socket.on('stockQuote',(jsonData){
        setState(() {
          list = jsonData;
          isLoading = false;
        });
      });
    });
super.initState();
}

dispose(){
    super.dispose();
  }

I get these errors:

Unhandled Exception: setState() called after dispose(): _StocksState#0faab(lifecycle state: defunct, not mounted)
This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose()
  • It happens because you're disposing the socket connection as the tab changes. Either you check if the Widget is mounted or you init the socket after the super call is done over initState. You can also do it over the changed dependencies method. – Mariano Zorrilla May 11 '20 at 04:45
  • @MarianoZorrilla , I tried removing the dispose function, check if widget is mounted, called the socket after super. but all return the same error – Gregory Sykes May 12 '20 at 04:16

1 Answers1

4

So apparently I found a solution to make the Socket.io load again.

Fix Code:

IO.Socket socket = IO.io('http://localhost:3000', <String, dynamic>{
    'transports': ['websocket'],
    'forceNew':true
}); 

So apparently I need to add 'forceNew': true so that the page loads the socket.io like new.

Source: How to close a socket.io connection