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

Flutter求助:实现无法同时选中的互斥切换按钮

实现互斥切换的水平按钮组

要实现两个按钮互斥选中的效果,核心是用一个状态变量跟踪当前选中项,动态切换按钮样式。以下是完整的实现方案:

代码实现

首先在你的State类里添加状态变量:

String? _selectedChoice; // 用'yes'/'no'标记选中项
bool isSafe = false;
String safetyMessage = '';

然后替换原有的按钮布局为水平排列的单选组:

Row(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    // Yes按钮
    ElevatedButton(
      style: ButtonStyle(
        backgroundColor: MaterialStateProperty.all(
          _selectedChoice == 'yes' ? Colors.green : Colors.white,
        ),
        foregroundColor: MaterialStateProperty.all(
          _selectedChoice == 'yes' ? Colors.white : Colors.green,
        ),
        side: MaterialStateProperty.all(
          BorderSide(
            color: _selectedChoice == 'yes' ? Colors.white : Colors.green,
          ),
        ),
      ),
      onPressed: () {
        setState(() {
          _selectedChoice = 'yes';
          isSafe = true;
          safetyMessage = 'Currently Safe: $isSafe';
        });
      },
      child: const Text('Yes'),
    ),
    const SizedBox(width: 12), // 按钮间距
    // No按钮
    ElevatedButton(
      style: ButtonStyle(
        backgroundColor: MaterialStateProperty.all(
          _selectedChoice == 'no' ? Colors.green : Colors.white,
        ),
        foregroundColor: MaterialStateProperty.all(
          _selectedChoice == 'no' ? Colors.white : Colors.green,
        ),
        side: MaterialStateProperty.all(
          BorderSide(
            color: _selectedChoice == 'no' ? Colors.white : Colors.green,
          ),
        ),
      ),
      onPressed: () {
        setState(() {
          _selectedChoice = 'no';
          isSafe = false;
          safetyMessage = 'Currently Safe: $isSafe';
        });
      },
      child: const Text('No'),
    ),
  ],
)

关键细节

  • 用_selectedChoice变量存储当前选中的按钮标识,点击时更新该值并调用setState触发UI更新
  • 每个按钮的背景色、文字色、边框色都根据_selectedChoice的值动态切换,实现选中/未选中的视觉区分
  • 如果需要默认选中某个按钮,只需在初始化时给_selectedChoice赋值(比如_selectedChoice = 'yes')
  • 用Row和SizedBox实现水平布局,保证按钮并排且有合理间距

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:43:19