Tab 更改后 Flutter Socket IO 无法获取数据

Gre*_*kes 1 sockets super socket.io flutter

因此,当我第一次打开该选项卡时,会显示来自 Socket.IO 的数据。但是当我更改选项卡并返回时,我无法从 Socket.IO 获取数据。

这是我的代码:

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();
  }
Run Code Online (Sandbox Code Playgroud)

我收到这些错误:

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()
Run Code Online (Sandbox Code Playgroud)

Gre*_*kes 5

显然我找到了一个解决方案来使 Socket.io 再次加载。

修复代码:

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

所以显然我需要添加 'forceNew': true 以便页面像新的一样加载 socket.io 。

来源:如何关闭 socket.io 连接