You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何BuildContext无mounted属性?Flutter 3.3.10调用报错

为什么BuildContext没有mounted属性,该如何解决报错?

我按照Flutter官方文档使用context.mounted进行判断,代码如下:

if (context.mounted) {

}

但收到错误提示:

The getter 'mounted' isn't defined for the type 'BuildContext'.
Try importing the library that defines 'mounted', correcting the name to the name of an existing getter, or defining a getter or field named 'mounted'.

已升级至最新稳定版Flutter:

Flutter 3.3.10 • channel stable •
https://github.com/flutter/flutter.git Framework • revision 135454af32
(2 weeks ago) • 2022-12-15 07:36:55 -0800 Engine • revision 3316dd8728
Tools • Dart 2.18.6 • DevTools 2.15.0

原因解析

BuildContext.mounted是Flutter 3.7版本才新增的扩展属性,你的Flutter版本为3.3.10,低于3.7,因此无法直接访问该属性。

解决方法

  1. 升级Flutter版本
    执行flutter upgrade将Flutter升级到3.7或更高版本。若stable频道暂未推送该版本,可先切换到beta频道升级,之后再切回stable:

    flutter channel beta
    flutter upgrade
    flutter channel stable
    
  2. 低版本兼容写法
    在不升级版本的情况下,可通过context获取关联的State对象,再访问其mounted属性:

    final state = context.findAncestorStateOfType<State>();
    if (state?.mounted == true) {
      // 执行需确保widget已挂载的操作
    }
    

    若在State类内部代码中,直接使用mounted即可,无需通过context。

内容的提问来源于stack exchange,提问作者Scorb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 05:45:24