Flutter:未处理的异常:刷新页面时在 dispose() 之后调用 setState()

Hem*_*zli 2 dart flutter

我正在开发一个纸牌游戏,它包括 2 个部分。

  1. 输入页
  2. 游戏页面

在 InputPage() 中,用户选择卡片,它有一个新的游戏按钮。但如果他/她不喜欢这些卡片,他/她可以重新开始游戏。InputPage() 中有一个重启游戏按钮,当用户点击它时,页面必须完全重启。我用 Navigator.of 方法做到了这一点。但是当用户转到 GamePage() 时,我收到了这样的错误:

Unhandled Exception: setState() called after dispose(): _GamePageState#d4518(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.
Run Code Online (Sandbox Code Playgroud)

我用 Navigator.pushReplacement 刷新页面。

你有什么更好的主意吗?

这是代码:

FlatButton(
          onPressed: () {
            Navigator.of(context).pushReplacement(new MaterialPageRoute(
                builder: (BuildContext context) => InputPage()));
          },
Run Code Online (Sandbox Code Playgroud)

Pul*_*epa 7

如果您setState()为不再出现在小部件树中的小部件调用State 对象,则会发生此错误

解决方案是在调用之前检查小部件状态类的挂载属性setState(),如下所示:

if (!mounted) return;

setState(){
  /** **/
 }
Run Code Online (Sandbox Code Playgroud)

或者:

if (mounted) {
  setState(() {
    /** **/
  });
}
Run Code Online (Sandbox Code Playgroud)