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

使用CustomerModel实现DropdownButton时出现重复值错误求助

解决DropdownButton重复value错误的方案

你的代码存在几个关键问题,直接导致了这个错误,按以下步骤修复:

  • 给DropdownMenuItem绑定value属性
    你生成DropdownMenuItem时只定义了child,完全没设置value字段,这会让所有选项的value默认是null,自然触发“多个item有相同value”的报错。修改代码:

    items: List.generate(
      allCustomers.length,
      (index) => DropdownMenuItem<CustomerModel>(
        value: allCustomers[index], // 必须添加这行,绑定对应的CustomerModel实例
        child: CustomTextBody(
          text: allCustomers[index].companyName,
        ),
      ),
    ),
    
  • 删除无效乱码代码
    代码中有一行无关乱码:exit是guy Heck [(parent interior](帮面 flip Indospin),这行破坏了代码结构,必须删掉。

  • 确认CustomerModel的相等判断逻辑正确
    重写==和hashCode时,必须基于实例的唯一标识(比如id字段),而不是默认的引用相等。示例实现:

    class CustomerModel {
      final String id;
      final String companyName;
    
      CustomerModel({required this.id, required this.companyName});
    
      @override
      bool operator ==(Object other) =>
          identical(this, other) ||
          other is CustomerModel &&
              runtimeType == other.runtimeType &&
              id == other.id;
    
      @override
      int get hashCode => id.hashCode;
    }
    
  • 检查选中值的有效性
    确保selectedCustomer的初始值是allCustomers列表中的某一个实例,或者当它为null时,selectedCustomer ?? allCustomers[0]确实指向列表中存在的项,避免出现不在选项列表中的值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 13:30:21