为何BuildContext无mounted属性?Flutter 3.3.10调用报错
我按照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,因此无法直接访问该属性。
解决方法
升级Flutter版本
执行flutter upgrade将Flutter升级到3.7或更高版本。若stable频道暂未推送该版本,可先切换到beta频道升级,之后再切回stable:flutter channel beta flutter upgrade flutter channel stable低版本兼容写法
在不升级版本的情况下,可通过context获取关联的State对象,再访问其mounted属性:final state = context.findAncestorStateOfType<State>(); if (state?.mounted == true) { // 执行需确保widget已挂载的操作 }若在
State类内部代码中,直接使用mounted即可,无需通过context。
内容的提问来源于stack exchange,提问作者Scorb

