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

Flutter中DropdownButton报错:值匹配项数量异常求助

Flutter DropdownButton 报错解决

错误信息

There should be exactly one item with [DropdownButton]'s value: Centimeter. 
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 892 pos 15: 'items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1'

问题核心

这个断言错误的本质是:DropdownButton的value属性对应的字符串,在items列表中找不到恰好一个匹配项,常见触发场景包括:

  • 初始值不在列表范围内
  • 变量名不匹配导致关联错误
  • 字符串大小写不一致
  • 列表中存在重复值

你的代码问题点

第一个DropdownButton

  • 初始值_startMeasure = ""是空字符串,但_measures列表里没有空字符串,导致Dropdown无法找到对应item,触发断言错误。
  • 错误信息提到的Centimeter是首字母大写格式,但你列表里的单位是小写的centimeter,如果代码其他地方误用了大写格式的value,也会导致匹配失败。

第二个DropdownButton

  • 变量名混乱:onChanged中更新的是_startMeasure,但Dropdown的value属性是_startMeasures(多了一个s),变量不匹配导致选中状态异常。
  • 未明确_measures2的内容,如果列表内存在重复值,也会触发错误。

解决方法

1. 修正初始值

将第一个Dropdown的初始值设为null,这样Dropdown会显示hint文本,而非尝试匹配不存在的空字符串:

String? _startMeasure; // 初始值设为null,而非空字符串
final List<String> _measures = [
    'centimeter',
    'millimeter',
    'meter',
    'kilometer',
    'inch',
    'foot',
    'yard',
    'miles',
  ];

Container(
  child: DropdownButtonHideUnderline(
    child: DropdownButton(
      hint: const Text("Unit"),
      items: _measures.map((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
      onChanged: (value) {
        setState(() {
          _startMeasure = value;
        });
      },
      value: _startMeasure,
    ),
  ),
),

2. 修复第二个Dropdown的变量关联

为第二个Dropdown单独定义选中变量,避免和第一个混淆:

// 单独定义第二个Dropdown的选中变量
String? _endMeasure;
// 确保_measures2列表值唯一、大小写统一
final List<String> _measures2 = [
    'centimeter',
    'millimeter',
    'meter',
    'kilometer',
    'inch',
    'foot',
    'yard',
    'miles',
  ];

Container(
  child: DropdownButtonHideUnderline(
    child: DropdownButton(
      hint: const Text("Unit"),
      items: _measures2.map((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
      onChanged: (value) {
        setState(() {
          _endMeasure = value; // 更新对应的变量
        });
      },
      value: _endMeasure, // 使用正确的变量
    ),
  ),
),

3. 统一字符串大小写

检查所有用到单位字符串的地方,确保大小写完全一致(比如全小写或全首字母大写),避免因大小写不匹配导致的item找不到问题。

4. 确保列表值唯一

检查_measures和_measures2列表,删除重复的单位字符串,重复值会触发“多个item有相同value”的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:27:11