Flutter中如何修改选中状态下按钮的背景颜色?
Flutter设置按钮选中状态背景颜色的几种方法
方法1:使用ToggleButtons组件
ToggleButtons原生支持选中状态管理,直接通过fillColor设置选中时的背景色,搭配selectedColor控制选中时的文字/图标颜色:
bool _isSelected = false; @override Widget build(BuildContext context) { return ToggleButtons( isSelected: [_isSelected], fillColor: Colors.blue, // 选中时的背景色 color: Colors.grey, // 未选中时的文字/图标颜色 selectedColor: Colors.white, // 选中时的文字/图标颜色 onPressed: (int index) { setState(() { _isSelected = !_isSelected; }); }, children: const [Text("按钮")], ); }
方法2:自定义带状态的普通按钮
通过StatefulWidget维护选中状态,用InkWell包裹容器,根据状态动态切换背景色:
class CustomSelectButton extends StatefulWidget { const CustomSelectButton({super.key}); @override State<CustomSelectButton> createState() => _CustomSelectButtonState(); } class _CustomSelectButtonState extends State<CustomSelectButton> { bool _isSelected = false; @override Widget build(BuildContext context) { return InkWell( onTap: () => setState(() => _isSelected = !_isSelected), child: Container( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), decoration: BoxDecoration( color: _isSelected ? Colors.green : Colors.grey[200], borderRadius: BorderRadius.circular(4), ), child: Text( _isSelected ? "已选中" : "未选中", style: TextStyle(color: _isSelected ? Colors.white : Colors.black), ), ), ); } }
方法3:改造ElevatedButton
给ElevatedButton绑定状态,通过ButtonStyle动态配置背景色:
bool _isSelected = false; @override Widget build(BuildContext context) { return ElevatedButton( onPressed: () => setState(() => _isSelected = !_isSelected), style: ElevatedButton.styleFrom( backgroundColor: _isSelected ? Colors.orange : Colors.grey[300], foregroundColor: _isSelected ? Colors.white : Colors.black, ), child: const Text("点击切换状态"), ); }
内容的提问来源于stack exchange,提问作者inzmam
相关产品推荐
相关产品推荐

