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

Flutter使用chips_choice库如何在Choice Chip首位添加静态'全部'选项

解决方案

你可以直接在拿到接口返回的分类列表后,在列表头部插入代表「全部」的虚拟分类数据,再渲染Chip列表即可,具体修改如下:

步骤1:修改Chip渲染方法

在buildDishMenuTypes中先构造合并后的数据源,再遍历生成ChoiceChip:

Widget buildDishMenuTypes(List<DishMenuTypesDishTypes> data) {
  // 构造带All的新列表
  final List<DishMenuTypesDishTypes> chipList = [
    // 插入首位的All虚拟数据
    DishMenuTypesDishTypes(
      dishTypesLocales: [
        DishMenuTypesDishTypesDishTypesLocales(name: "All")
      ]
    ),
    ...data
  ];
  // 用Wrap承载多个Chip,你也可以换成chips_choice库的ChipsChoice组件
  return Wrap(
    spacing: 8,
    runSpacing: 8,
    children: List.generate(chipList.length, (index) {
      return ChoiceChip(
        label: Text(chipList[index].dishTypesLocales![0]!.name!),
        selected: menuIndex == index,
        selectedColor: redColor,
        onSelected: (bool selected) {
          setState(() {
            menuIndex = selected ? index : 0;
          });
          // 此处可添加选中后的业务逻辑,比如index为0时查询全部菜品
        },
        backgroundColor: greyColor,
        labelStyle: TextStyle(
          color: whiteColor,
          fontWeight: FontWeight.bold
        ),
      );
    }),
  );
}

步骤2:可选优化(使用chips_choice库原生组件)

如果你要使用chips_choice: ^2.0.1库的原生能力实现,写法更简洁:

Widget buildDishMenuTypes(List<DishMenuTypesDishTypes> data) {
  // 构造选项列表
  final List<String> options = [
    "All",
    ...data.map((item) => item.dishTypesLocales![0]!.name!)
  ];
  return ChipsChoice<int>.single(
    value: menuIndex,
    onChanged: (val) => setState(() => menuIndex = val),
    choiceItems: C2Choice.listFrom<int, String>(
      source: options,
      value: (i, v) => i,
      label: (i, v) => v,
    ),
    choiceStyle: C2ChipStyle(
      backgroundColor: greyColor,
      selectedColor: redColor,
      foregroundStyle: TextStyle(
        color: whiteColor,
        fontWeight: FontWeight.bold
      ),
    ),
  );
}

注意事项

  • 上述代码默认你接口返回的dishTypesLocales列表非空且第一个元素的name有值,你可以根据自身业务的容错需求补充空判断逻辑
  • 原有代码中menuIndex默认初始值为0,刚好对应首位的「All」选项,不需要修改初始化逻辑

内容的提问来源于stack exchange,提问作者Mohammed Nabil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 05:18:05