Flutter中如何实现单选模式的Filter Chips
如何将Flutter Filter Chips从多选改为单选模式
要实现Filter Chips的单选模式,核心是把原来存储多选状态的列表改为单个变量记录当前选中项,同时调整选中判断和点击逻辑,具体修改如下:
1. 修改状态变量类型
将原来的列表类型改为单个字符串,用来保存当前选中的年龄选项:
final items3 = [ "All", "0-2 Years", "2-4 Years", "5-7 Years", "8-13 Years", "14+ Years" ]; // 替换原来的List<String> age = [items3.first]; late String selectedAge = items3.first;
2. 调整FilterChip的选中判断逻辑
把selected属性的判断从列表包含改为直接对比当前选中项:
selected: e == selectedAge,
3. 修改点击回调逻辑
点击芯片时,直接将当前选项赋值给selectedAge,同时修正filter函数的参数(原来固定传'0-2'是硬编码,现在传选中的实际值):
onSelected: (bool value) { selectedAge = e; filter(age: e); // 传递当前选中的年龄选项 setState(() {}); },
修改后的完整代码
final items3 = [ "All", "0-2 Years", "2-4 Years", "5-7 Years", "8-13 Years", "14+ Years" ]; late String selectedAge = items3.first; Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Text('AGE', style: GoogleFonts.poppins( color: const Color(0xffffffff), fontSize: 20, fontWeight: FontWeight.w700, letterSpacing: 0.8, )), ]), Padding( padding: const EdgeInsets.only(top: 15, left: 20), child: Wrap( spacing: 8, runSpacing: 15, children: items3 .map( (e) => FilterChip( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), backgroundColor: Colors.white, selectedColor: const Color(0xff6fedf6), label: Container( height: 46, width: 80, alignment: Alignment.center, child: Text(e), ), labelStyle: GoogleFonts.poppins( textStyle: const TextStyle( color: Colors.black, fontSize: 14, fontWeight: FontWeight.w500, letterSpacing: 0.5, ), ), selected: e == selectedAge, onSelected: (bool value) { selectedAge = e; filter(age: e); setState(() {}); }), ) .toList(), ), ),
这样修改后,Filter Chips就会变成单选模式:每次只能选中一个选项,点击新选项时会自动取消之前的选中状态。
内容的提问来源于stack exchange,提问作者Divya
相关产品推荐
相关产品推荐

