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

Flutter联动下拉框报错:检测到重复值的DropdownMenuItem

Flutter联动下拉框错误解决指南

问题核心

你遇到的Either zero or 2 or more [DropdownMenuItem]s were detected with the same value错误,本质是下拉框选中值与选项列表不匹配,或选项存在重复value,以下是具体问题点和修复方案:


1. 初始化数据笔误

你的initState中存在未定义变量错误:dropDownItem.add(...)里的dropDownItem未声明,应该改为dropDownItemType.add,否则父下拉框初始仅含"Services"选项,默认值"Product"无法正常加载,直接导致联动逻辑混乱。

修正后的initState:

void initState() {
  dropDownItemType.add({"id": 1, "name": "Product"});
  dropDownItemType.add({"id": 2, "name": "Services"});

  categoryMasters = [
    {
      "ID": 1,
      "Name": "Meal",
      "ParentId": 1,
    },
    {
      "ID": 2,
      "Name": "Health",
      "ParentId": 1,
    },
    {
      "ID": 3,
      "Name": "Massage",
      "ParentId": 2,
    },
    {
      "ID": 4,
      "Name": "Delivery",
      "ParentId": 2,
    },
  ];
  super.initState();
}

2. 子下拉框onChanged逻辑错误

你在子下拉框回调中强制将categoryId设置为categoryMasters[0]["ParentId"].toString()(固定为"1"),这会导致:

  • 选择Services下的子选项时,选中值被强制改为"1",但Services对应的子选项ID是3、4,出现选中值与选项不匹配的情况
  • 切回Product类型时,子选项ID为1、2,此时错误的选中值状态触发重复value检测错误

修正后的子下拉框回调:

(onChangedVal) {
  setState(() {
    this.categoryId = onChangedVal;
  });
  // 通过选中ID匹配分类名称
  final selectedCategory = categoryMasters.firstWhere(
    (item) => item["ID"].toString() == onChangedVal,
    orElse: () => {},
  );
  getStringCategory = selectedCategory["Name"];
  print("Cat Name: ${getStringCategory}");
},

3. 优化父下拉框类型名称获取逻辑

原代码通过索引获取类型名称的方式存在索引不匹配风险,改为通过firstWhere查找更可靠:

修正后的父下拉框回调中getStringType的获取部分:

itemTypeId = onChangedVal;
final selectedType = dropDownItemType.firstWhere(
  (item) => item["id"].toString() == itemTypeId,
  orElse: () => {},
);
getStringType = selectedType["name"];

4. 额外注意点

  • 父下拉框切换时已正确将categoryId置为null,确保子下拉框随父选项重置为未选中状态
  • 修正后所有下拉框选项的value(父框的id、子框的ID)均为唯一值,彻底规避重复value检测错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:30:43