Flutter使用RoundIconButton时build阶段调用setState报错如何解决
问题原因与解决方案
1 构建阶段触发setState报错修复
这个报错的根本原因是你在RoundIconButton中错误地立即执行了onPressed回调:你当前的写法onPressed: onPressed()带括号,会在组件执行build方法时直接调用传入的add函数,而add内部包含setState逻辑,此时组件还在构建过程中,无法触发重绘,就会抛出对应的报错。
同时你当前两个按钮都绑定了同一个add回调,减号按钮的逻辑也不符合需求。
修复方法:
首先修改RoundIconButton的实现,调整onPressed的绑定逻辑和类型声明:
class RoundIconButton extends StatelessWidget { RoundIconButton({required this.icon, required this.onPressed}); final IconData icon; // 优化回调类型为VoidCallback,明确是无参数无返回值的点击回调 final VoidCallback onPressed; @override Widget build(BuildContext context) { return RawMaterialButton( // 去掉括号,仅传递函数引用,点击时才会执行回调 onPressed: onPressed, child: Icon(icon, color: Colors.white,), shape: CircleBorder(), fillColor: Color(0xff4c4f5e), constraints: BoxConstraints.tightFor( width: 56.0, height: 56.0, ), ); } }
之后修改按钮处的绑定逻辑,区分加减操作:
Row( mainAxisAlignment: MainAxisAlignment.center, children: [ RoundIconButton( // 减号按钮点击体重减1,增加边界判断避免体重为负数 onPressed: () => setState(() { if(weight > 0) weight--; }), icon: FontAwesomeIcons.minus, ), SizedBox( width: 10.0, ), RoundIconButton( // 加号按钮点击体重加1 onPressed: () => setState(() => weight++), icon: FontAwesomeIcons.plus, ), ], )
2 RenderFlex溢出问题修复
这个问题是子组件尺寸超出了父组件的约束范围导致的,针对你的场景做以下优化即可:
给显示体重的Text组件增加适配逻辑,避免字号太大超出边界:
// 用FittedBox包裹Text,自动缩放适配父容器尺寸 FittedBox( fit: BoxFit.contain, child: Text( weight.toString(), style: kNumberTextStyle, maxLines: 1, ), )
如果仍然存在溢出,检查上层ReusableCard组件是否正确声明了尺寸约束,避免Column的内容超出卡片的显示范围即可。
内容的提问来源于stack exchange,提问作者Chirashish Jeena
相关产品推荐
相关产品推荐

