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

Flutter Stateful Widget场景下点击SVG颜色不变如何更新状态?

问题原因及解决方法
  • 父组件状态更新未触发重绘:父组件funcForTapsandClicks方法修改buttonChecked变量后未调用setState,父组件不会重新构建,子组件无法拿到最新状态值。
  • 子组件未关联父组件状态:ToolSetButton子组件未定义接收选中状态的参数,内部判断颜色时使用的buttonChecked和父组件维护的状态无关联。
具体修改步骤
  1. 修改父组件点击回调方法,调用setState触发重绘:
funcForTapsandClicks(myButtonList tappedOn) {
  if (tappedOn == myButtonList.Two ){
    print('Two');
    setState(() {
      buttonChecked = !buttonChecked;
    });
  }
}
  1. 父组件调用子组件时新增传入选中状态参数:
ToolSetButton(
  svgPicPath: svgVectorImagePath,
  buttonType: myButtonTypeList.SVGOnly,
  checkedColour: Colors.green,
  unCheckedColour: Colors.grey,
  width: 80,
  height: 80,
  isChecked: buttonChecked, // 新增本行传入选中状态
  functionReceiverforButtonandSVG: () { funcForTapsandClicks(myButtonList.Two);}
)
  1. 子组件新增接收选中状态的参数:
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();
}
  1. 子组件设置SVG颜色时使用父组件传入的状态判断:
SvgPicture.asset(
  widget.svgPicPath!,
  color: widget.isChecked 
    ? widget.checkedColour 
    : widget.unCheckedColour
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:09:06