Flutter新手求助:实现按钮组选中时显示/隐藏勾选图标
实现带选中勾选图标的Flutter按钮组
直接用StatefulWidget维护选中项状态,配合自定义按钮组件就能实现你要的效果,比Radio组件更灵活。下面是完整可运行的代码:
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text("选中按钮示例")), body: const ButtonGroupExample(), ), ); } } class ButtonGroupExample extends StatefulWidget { const ButtonGroupExample({super.key}); @override State<ButtonGroupExample> createState() => _ButtonGroupExampleState(); } class _ButtonGroupExampleState extends State<ButtonGroupExample> { // 维护当前选中的按钮索引,初始为null表示未选中任何按钮 int? _selectedIndex; // 按钮选项列表 final List<String> _buttonLabels = ["选项1", "选项2", "选项3", "选项4"]; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(16.0), child: Wrap( spacing: 8.0, // 按钮之间的水平间距 children: List.generate(_buttonLabels.length, (index) { return ElevatedButton( style: ElevatedButton.styleFrom( // 选中时改变按钮背景色,增强视觉反馈 backgroundColor: _selectedIndex == index ? Colors.blue[700] : null, ), onPressed: () { setState(() { _selectedIndex = index; }); }, child: Row( mainAxisSize: MainAxisSize.min, children: [ // 根据选中状态显示/隐藏勾选图标 if (_selectedIndex == index) const Icon(Icons.check, size: 16, color: Colors.white), if (_selectedIndex == index) const SizedBox(width: 4), // 图标与文字的间距 Text(_buttonLabels[index]), ], ), ); }), ), ); } }
关键逻辑说明
- 用
_selectedIndex变量记录当前选中的按钮位置,通过setState()更新状态触发UI刷新 - 在按钮内部通过
if条件判断,仅当按钮处于选中状态时渲染勾选图标 - 可通过
ElevatedButton.styleFrom调整选中按钮的样式,强化选中状态的视觉提示 - 用
Wrap组件让按钮组自动换行,适配不同屏幕宽度
如果需要多选效果,只需修改状态变量和点击逻辑:
// 把单个选中索引改成选中索引集合 Set<int> _selectedIndices = {}; // 点击事件切换选中状态 onPressed: () { setState(() { if (_selectedIndices.contains(index)) { _selectedIndices.remove(index); } else { _selectedIndices.add(index); } }); } // 判断选中状态的条件改为 if (_selectedIndices.contains(index))
内容的提问来源于stack exchange,提问作者caleb teshale
相关产品推荐
相关产品推荐

