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

Flutter使用DropdownButton时触发_AssertionError报错如何解决?

Flutter DropdownButton 断言错误原因及修复方案

已触发异常:
_AssertionError ('package:flutter/src/material/dropdown.dart':断言失败,第915行第15位:'items == null || items.isEmpty || value == null || items.where((DropdownMenuItem item) { return item.value == value; }).length == 1':[DropdownButton]的value值0对应的选项必须有且仅有1个,当前检测到存在0个、2个或更多个value值相同的[DropdownMenuItem]。

报错核心原因

这个报错是DropdownButton内置的强制校验触发的,只有两种情况会触发该断言:

  • 你给DropdownButton的value属性绑定的值,不在items列表所有选项的value范围内,比如items的value集合是[1,2,3],但value赋值为0,框架找不到匹配的选项
  • items列表中存在至少两个DropdownMenuItem的value值完全一致,框架无法确定要匹配哪一个选项

如果使用自定义类作为value值,没有重写==运算符和hashCode的情况下,即使两个对象的属性完全相同,Dart也会判定为不同对象,也会出现第一种找不到匹配项的情况

排查修复步骤

  • 检查DropdownButton的value初始值,确认该值存在于items所有选项的value集合中,如果需要默认不选中,可直接将value赋值为null,符合框架校验规则
  • 遍历检查items列表所有选项的value值,确保没有重复值,相同value的选项仅能存在一个
  • 若使用自定义类作为value,必须重写类的==运算符和hashCode,保证Dart可以正确判定两个value是否相等,示例代码如下:
class User {
  final int id;
  final String name;
  User(this.id, this.name);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is User && runtimeType == other.runtimeType && id == other.id;

  @override
  int get hashCode => id.hashCode;
}
  • 若下拉选项是异步加载的,要保证items加载完成后再给value赋值,避免赋值时items为空找不到对应选项

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:54:01