如何在RaisedButton被选中时更改其颜色
问题原因
- 状态变量
isButtonPressed被定义为ChoiceChip方法内的局部变量,每次setState触发页面重绘时,ChoiceChip方法会重新执行,isButtonPressed会被重置为初始值false,因此按钮样式始终不会发生变化。
修复方案
推荐将自定义的ChoiceChip抽成独立的StatefulWidget,让每个按钮自己维护选中状态,示例代码如下:
class CustomChoiceChip extends StatefulWidget { final String chipName; const CustomChoiceChip({super.key, required this.chipName}); @override State<CustomChoiceChip> createState() => _CustomChoiceChipState(); } class _CustomChoiceChipState extends State<CustomChoiceChip> { // 状态变量定义在State类中,重绘不会被重置 bool isButtonPressed = false; @override Widget build(BuildContext context) { return Container( child: RaisedButton( color: isButtonPressed ? Colors.green : Colors.red, child: Text( widget.chipName, style: const TextStyle( color: Colors.black, ), ), onPressed: () { setState(() { isButtonPressed = !isButtonPressed; }); }, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), side: BorderSide( color: isButtonPressed ? Colors.green : Colors.red, ), ), ), ); } }
使用时直接调用CustomChoiceChip(chipName: "你的按钮文本")即可。
如果需要父组件统一管理所有按钮的选中状态,可以将isButtonPressed和选中回调作为参数传入自定义组件,不在组件内部维护状态即可。
内容的提问来源于stack exchange,提问作者dosytres
相关产品推荐
相关产品推荐

