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

Flutter FilterChip单选功能实现咨询:是否需更换组件?

Flutter FilterChip 实现单选功能方案

完全可以基于现有FilterChip实现单选,没必要更换组件;当然也可以选择更贴合单选场景的ChoiceChip,两种方案如下:

方案一:修改现有FilterChip代码实现单选

原来的代码用列表selectedCityCategory存储选中项,改成单个变量存储选中的城市即可:

  1. 先定义单个选中变量(替换原来的selectedCityCategory):
String? selectedCity;
  1. 修改FilterChip的selected属性和onSelected回调:
Row(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: cityCategory
      .map((city) => Padding(
            padding: EdgeInsets.symmetric(horizontal: screenWidth * 0.05),
            child: FilterChip(
              side: BorderSide(width: 2, color: ColorApp.light.get()),
              padding: const EdgeInsets.all(10),
              checkmarkColor: Colors.white,
              selectedColor: ColorApp.dark.get(),
              labelStyle: GoogleFonts.elMessiri(
                color: Colors.white,
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
              backgroundColor: ColorApp.middle.get(),
              shadowColor: ColorApp.dark.get(),
              elevation: 5,
              label: Text(city),
              // 改为判断当前城市是否等于选中的城市
              selected: selectedCity == city,
              onSelected: (selected) {
                setState(() {
                  if (selected) {
                    // 选中时直接赋值为当前城市,自动取消之前的选中项
                    selectedCity = city;
                  } else {
                    // 取消选中当前城市时置空
                    selectedCity = null;
                  }
                });
              },
            ),
          ))
      .toList(),
)

方案二:改用ChoiceChip实现单选

ChoiceChip本身就是为单选场景设计的组件,用法和FilterChip类似,语义更明确:

Row(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: cityCategory
      .map((city) => Padding(
            padding: EdgeInsets.symmetric(horizontal: screenWidth * 0.05),
            child: ChoiceChip(
              side: BorderSide(width: 2, color: ColorApp.light.get()),
              padding: const EdgeInsets.all(10),
              selectedColor: ColorApp.dark.get(),
              labelStyle: GoogleFonts.elMessiri(
                color: Colors.white,
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
              backgroundColor: ColorApp.middle.get(),
              shadowColor: ColorApp.dark.get(),
              elevation: 5,
              label: Text(city),
              selected: selectedCity == city,
              onSelected: (selected) {
                setState(() {
                  selectedCity = selected ? city : null;
                });
              },
            ),
          ))
      .toList(),
)

两种方案都能实现单选需求,如果你习惯现有FilterChip的样式,直接改方案一就行;如果想更贴合单选的语义,选方案二更合适。

内容的提问来源于stack exchange,提问作者Othman Sami Dheyab

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 03:42:05