Flutter中StatefulWidget非final变量引发ParentDataWidget误用异常如何解决
问题原因与解决方案
1. 「Incorrect use of ParentDataWidget」异常原因
这个异常和counter变量没有关系,是Expanded组件使用错误导致的:Expanded只能作为Row、Column、Flex这类Flex布局组件的子组件使用,你当前代码中把Expanded放在了Container的child位置,Container不属于Flex类组件,因此触发了该异常。
2. StatefulWidget的@immutable警告原因
StatefulWidget本身被标记为不可变类,所有属性必须声明为final,不能在Widget类中存储需要修改的可变状态,可变状态必须放到对应的State子类中存储。
修复后的完整代码
class TopInfoBanner extends StatefulWidget { // Widget类仅存储不需要修改的配置类属性 TopInfoBanner({Key? key}) : super(key: key); @override State<TopInfoBanner> createState() => _TopInfoBannerState(); } class _TopInfoBannerState extends State<TopInfoBanner> { final Color textColor = cSecondaryColor; // 可变counter移到State类中存储 int counter = 0; @override Widget build(BuildContext context) { return Container( height: 42.0, color: cBoxColor, // 删掉错误使用的Expanded组件 child: Padding( padding: const EdgeInsets.symmetric(vertical: 2.0), child: InkWell( onTap: () { setState( () { // 直接修改State内的counter变量 counter++; }, ); }, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ if (counter % 3 == 0) infoBuilder('text 1', Icons.update_sharp), if (counter % 3 == 1) infoBuilder( 'text 2', Icons.ac_unit_sharp), if (counter % 3 == 2) infoBuilder('text 3', Icons.gpp_good_outlined), ], ), ), ), ); } Padding infoBuilder(String text, IconData icon) { return Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: Row( children: [ Icon( icon, color: textColor, ), Text( text, style: Theme.of(context) .textTheme .bodyText1! .copyWith(color: textColor), ), ], ), ); } }
核心修改点
- 删除了Container下错误嵌套的Expanded组件,解决ParentData相关异常
- 将counter变量从StatefulWidget类迁移到State子类中,符合StatefulWidget的不可变约定,同时满足状态修改需求
- setState中直接修改State内的counter变量即可触发UI刷新
内容的提问来源于stack exchange,提问作者Root
相关产品推荐
相关产品推荐

