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
相关产品推荐
相关产品推荐

