首页 > 解决方案 > Flutter:未处理的异常:刷新页面时发生在dispose()之后调用的setState()

问题描述

我正在开发一款纸牌游戏,它包括 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.

我用 Navigator.pushReplacement 刷新页面。

你有更好的主意吗?

这是代码:

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

标签: flutterdart

解决方案


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

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

if (!mounted) return;

setState(){
  /** **/
 }

或者:

if (mounted) {
  setState(() {
    /** **/
  });
}

推荐阅读