Flutter Stateful Widget场景下点击SVG颜色不变如何更新状态?
问题原因及解决方法
- 父组件状态更新未触发重绘:父组件
funcForTapsandClicks方法修改buttonChecked变量后未调用setState,父组件不会重新构建,子组件无法拿到最新状态值。 - 子组件未关联父组件状态:
ToolSetButton子组件未定义接收选中状态的参数,内部判断颜色时使用的buttonChecked和父组件维护的状态无关联。
具体修改步骤
- 修改父组件点击回调方法,调用
setState触发重绘:
funcForTapsandClicks(myButtonList tappedOn) { if (tappedOn == myButtonList.Two ){ print('Two'); setState(() { buttonChecked = !buttonChecked; }); } }
- 父组件调用子组件时新增传入选中状态参数:
ToolSetButton( svgPicPath: svgVectorImagePath, buttonType: myButtonTypeList.SVGOnly, checkedColour: Colors.green, unCheckedColour: Colors.grey, width: 80, height: 80, isChecked: buttonChecked, // 新增本行传入选中状态 functionReceiverforButtonandSVG: () { funcForTapsandClicks(myButtonList.Two);} )
- 子组件新增接收选中状态的参数:
class ToolSetButton extends StatefulWidget { final double width; final double height; final Color checkedColour; final Color unCheckedColour; final myButtonTypeList buttonType; final String? svgPicPath; final Widget? icon; final VoidCallback functionReceiverforButtonandSVG; final bool isChecked; // 新增本行定义参数 const ToolSetButton({ Key? key, required this.width, required this.height, this.checkedColour = iconColourUnchecked, this.unCheckedColour = iconColourChecked, required this.buttonType, this.svgPicPath, this.icon, required this.functionReceiverforButtonandSVG, required this.isChecked, // 构造函数新增本行 }) : super(key: key); @override State<ToolSetButton> createState() => _ToolSetButtonState(); }
- 子组件设置SVG颜色时使用父组件传入的状态判断:
SvgPicture.asset( widget.svgPicPath!, color: widget.isChecked ? widget.checkedColour : widget.unCheckedColour )
内容的提问来源于stack exchange,提问作者Pretty_Girl
相关产品推荐
相关产品推荐

