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

Flutter Socket IO can't get data after tab is changed

因此,当我第一次打开该选项卡时,会出现来自 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();
  }

我收到这些错误:

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()

显然,我找到了使 Socket.io 再次加载的解决方案。

修复代码:

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

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

来源: