Flutter中如何实现点击TextButton后切换颜色并保持选中状态
实现方案
结论
该需求完全可以实现,核心是通过State状态变量记录选中的班级项,点击按钮时调用setState触发UI重绘,动态切换按钮样式即可。
具体实现步骤
- 新增状态变量存储选中项
在_property_selectionState类中新增变量,记录当前选中的班级:
class _property_selectionState extends State<property_selection> { // 新增:存储当前选中的班级 String? _selectedClass; @override Widget build(BuildContext context) { // 原有逻辑不变 } }
- 给TextButton添加点击更新逻辑
修改每个班级对应的TextButton的onPressed回调,点击时更新选中状态:
以Class 01为例:
onPressed: () { setState(() { _selectedClass = 'Class 01'; }); },
Class 02、Class 03对应的回调分别把赋值改为'Class 02'、'Class 03'即可。
- 动态绑定按钮样式
修改每个TextButton的style属性,根据当前选中状态切换背景色、文字色(可按需替换为你指定的色值):
同样以Class 01为例:
style: ButtonStyle( side: MaterialStateProperty.all( BorderSide(width: 2, color: _selectedClass == 'Class 01' ? Colors.red : Colors.grey), ), backgroundColor: MaterialStateProperty.all( _selectedClass == 'Class 01' ? Colors.red : Colors.white ), foregroundColor: MaterialStateProperty.all( _selectedClass == 'Class 01' ? Colors.white : Colors.black ), // 其余padding、textStyle属性保持不变 ),
其余班级按钮对应修改判断的班级名称即可。
优化建议
如果后续班级数量会增加,可把班级列表抽为数组,通过循环生成按钮,减少重复代码:
// 预先定义班级列表 final List<String> _classList = ['Class 01', 'Class 02', 'Class 03']; // build方法中生成按钮部分替换为: ... SizedBox(height: 15.0,), // 循环生成所有班级按钮 for (final className in _classList) Container( margin: EdgeInsets.fromLTRB(75, 0, 75, 0), padding: EdgeInsets.fromLTRB(0, 0, 0, 0), height: 60.0, child: TextButton( onPressed: () { setState(() { _selectedClass = className; }); }, child: SizedBox( width: double.infinity, child: Text( className, textAlign: TextAlign.left, ), ), style: ButtonStyle( side: MaterialStateProperty.all( BorderSide(width: 2, color: _selectedClass == className ? Colors.red : Colors.grey), ), backgroundColor: MaterialStateProperty.all( _selectedClass == className ? Colors.red : Colors.white ), foregroundColor: MaterialStateProperty.all( _selectedClass == className ? Colors.white : Colors.black ), padding: MaterialStateProperty.all( EdgeInsets.symmetric(vertical: 10, horizontal: 50)), textStyle: MaterialStateProperty.all( TextStyle(fontSize: 15), ), ), ), ), SizedBox(height: 10.0,), ...
内容的提问来源于stack exchange,提问作者Maahdi.Codes
相关产品推荐
相关产品推荐

