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

Flutter下拉框报错:检测到0个/2个及以上相同值的DropdownMenuItem

Flutter 下拉框联动报错:Either zero or 2 or more [DropdownMenuItem]s were detected with the same value

问题场景

两级联动下拉框:

  1. 第一级为银行列表,选中后调用API加载对应银行的分支列表
  2. 首次选择分支功能正常,但切换到包含同名分支的其他银行(如印度银行与Axis Bank)时,触发报错:

    Either zero or 2 or more [DropdownMenuItem]s were detected with the same value

  3. 分支列表为空或无同名分支时无此问题,切换回首次选中的银行也正常

已尝试方案

  1. 重写Branch类的==运算符,对比branchId和descriptionEn,但未生效
  2. 在分支数据加载成功时,执行清空操作:
    else if (state is GetBranchSuccessState) {
        selectedBranch = null;
        ifsc = null;
        branchList=[];
        branchList = state.data.data!;
      } 
    

解决方案

1. 完善Branch类的对象相等判断(核心修复)

Flutter的Dropdown组件在判断DropdownMenuItem的value是否重复时,会同时依赖**==运算符和hashCode**,仅重写==是不够的。由于branchId是分支的唯一标识,只需基于它实现相等判断:

修改后的Branch类代码:

class Branch {
  final int? bankId;
  final int? branchId;
  final String? ifscCode;
  final String? descriptionEn;
  final dynamic descriptionLl;
  
  Branch({
    this.bankId,
    this.branchId,
    this.ifscCode,
    this.descriptionEn,
    this.descriptionLl,
  });

  factory Branch.fromJson(Map<String, dynamic> json) => Branch(
        bankId: json["bank_id"],
        branchId: json["branch_id"],
        ifscCode: json["ifsc_code"],
        descriptionEn: json["description_en"],
        descriptionLl: json["description_ll"],
      );
  
  @override
  String toString() {
    return descriptionEn.toString();
  }

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Branch &&
          runtimeType == other.runtimeType &&
          branchId == other.branchId; // 仅比较唯一标识branchId

  @override
  int get hashCode => branchId.hashCode; // 基于branchId生成hashCode
}

2. 确保分支列表与选中状态的正确更新

  • 确认branchList是完全替换为新数据(当前代码的branchList = state.data.data!已满足,避免在原列表上修改)
  • 确保自定义下拉组件QDropDownList中:
    • DropdownButton的value严格绑定selectedBranch
    • 每个DropdownMenuItem的value直接传入Branch对象,而非名称等字段
    • 分支列表更新时,组件会重新构建所有DropdownMenuItem

3. 验证状态重置逻辑

切换银行后,selectedBranch必须被置为null,避免残留的旧分支对象与新列表中的同名分支对象产生相等判断冲突(当前代码已实现,需确保状态更新能触发组件重建)

内容的提问来源于stack exchange,提问作者Farhana Naaz Ansari

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 23:55:16