Flutter:点击文本选项时动态置灰另一选项的实现方法
Flutter实现点击选项后另一选项置灰的方案
核心思路是通过状态管理维护当前选中的选项,根据选中状态动态调整两个文本选项的样式(颜色)和交互状态。以下是两种实用的实现方式:
方式一:用InkWell包裹Text(灵活自定义样式)
这种方式完全可控,适合需要精准调整外观的场景:
import 'package:flutter/material.dart'; class OptionSelector extends StatefulWidget { const OptionSelector({super.key}); @override State<OptionSelector> createState() => _OptionSelectorState(); } class _OptionSelectorState extends State<OptionSelector> { // 维护选中状态:true表示选中选项A,false表示选中选项B bool _isOptionASelected = false; @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ // 选项A InkWell( onTap: () { setState(() { _isOptionASelected = true; }); }, child: Text( "选项A", style: TextStyle( fontSize: 18, // 未选中时置灰,选中时用主题色 color: _isOptionASelected ? Theme.of(context).primaryColor : Colors.grey, fontWeight: _isOptionASelected ? FontWeight.bold : FontWeight.normal, ), ), ), const SizedBox(width: 40), // 选项B InkWell( onTap: () { setState(() { _isOptionASelected = false; }); }, child: Text( "选项B", style: TextStyle( fontSize: 18, color: !_isOptionASelected ? Theme.of(context).primaryColor : Colors.grey, fontWeight: !_isOptionASelected ? FontWeight.bold : FontWeight.normal, ), ), ), ], ); } }
关键说明:
- 用
_isOptionASelected布尔变量记录选中状态,点击时通过setState更新状态 - 每个选项的文本颜色根据状态动态切换:选中的用主题色,未选中的设为灰色
InkWell提供点击反馈(水波纹效果),如果不需要可以换成GestureDetector
方式二:自定义TextButton样式(保留按钮特性)
如果需要保留TextButton的按钮特性(比如最小点击区域、默认交互反馈),可以通过ButtonStyle自定义样式:
import 'package:flutter/material.dart'; class ButtonOptionSelector extends StatefulWidget { const ButtonOptionSelector({super.key}); @override State<ButtonOptionSelector> createState() => _ButtonOptionSelectorState(); } class _ButtonOptionSelectorState extends State<ButtonOptionSelector> { bool _isOptionASelected = false; @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ TextButton( onPressed: () { setState(() { _isOptionASelected = true; }); }, style: TextButton.styleFrom( foregroundColor: _isOptionASelected ? Theme.of(context).primaryColor : Colors.grey, // 可选:未选中时禁用按钮(完全不可点击) // disabledForegroundColor: Colors.grey, // enabled: _isOptionASelected ? true : false, ), child: const Text("选项A"), ), const SizedBox(width: 40), TextButton( onPressed: () { setState(() { _isOptionASelected = false; }); }, style: TextButton.styleFrom( foregroundColor: !_isOptionASelected ? Theme.of(context).primaryColor : Colors.grey, // enabled: !_isOptionASelected ? true : false, ), child: const Text("选项B"), ), ], ); } }
关键说明:
- 通过
TextButton.styleFrom的foregroundColor控制文本颜色,实现置灰效果 - 如果需要完全禁用未选中的选项,取消注释
enabled和disabledForegroundColor配置,这样未选中的按钮不仅置灰,还无法响应点击
为什么之前用TextButton效果不符合预期?
大概率是没有正确绑定状态到按钮的样式属性,或者TextButton的默认主题样式覆盖了自定义颜色。通过明确指定foregroundColor或者disabledForegroundColor,可以避免样式冲突。
内容的提问来源于stack exchange,提问作者kelompok7 iot
相关产品推荐
相关产品推荐

