Flutter DropdownButton报0或多个同值项断言错误解决方案
问题场景
需要实现省份选择下拉列表,计划先将下拉组件保存为DropdownButton类型的实例,再放入Scaffold组件中使用。同类问题的通用方案无法适配当前场景,初始实现代码如下:
List<String> provinces = [ 'عمان', 'إربد', 'الزرقاء', 'المفرق', 'الطفيلة', 'عجلون', 'معان', 'الكرك', 'مادبا', 'العقبة', 'البلقاء', 'جرش' ]; String dropDownValue = ""; final provincesField = DropdownButton<String>( value: dropDownValue, icon: Icon(Icons.keyboard_arrow_down), items: provinces.map((String items) { return DropdownMenuItem(value: items, child: Text(items)); }).toList(), onChanged: (String? newValue) { setState(() { dropDownValue = newValue!; }); }, );
运行报错
组件运行时无法正确匹配列表项,抛出如下断言错误:
The following assertion was thrown building RegistrationScreen(dirty, state: _RegistrationScreenState#b01ae): There should be exactly one item with [DropdownButton]'s value: . Either zero or 2 or more [DropdownMenuItem]s were detected with the same value 'package:flutter/src/material/dropdown.dart': package:flutter/…/material/dropdown.dart:1 Failed assertion: line 882 pos 15: 'items == null || items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) { return item.value == value; }).length == 1'
错误原因
Flutter 的DropdownButton组件强制要求:传入的value必须满足要么为null,要么在所有菜单项的value中有且仅有一个匹配项。
当前代码中初始化的dropDownValue为空字符串,而provinces列表里不存在值为空字符串的选项,组件无法找到唯一匹配当前value的菜单项,因此触发框架断言校验报错,并非组件读取列表为空。
修复方案
二选一即可:
- 方案1:默认选中第一个省份,将初始值设置为列表中存在的元素
// 初始值直接取列表第一项,保证和菜单项匹配 String dropDownValue = provinces.first;
- 方案2:需要默认空选中状态时,将value初始值设为null,对应调整类型为可空类型
// 声明为可空String,初始值为null String? dropDownValue = null; final provincesField = DropdownButton<String>( value: dropDownValue, icon: Icon(Icons.keyboard_arrow_down), // 可增加hint提示空选中状态 hint: Text("请选择省份"), items: provinces.map((String items) { return DropdownMenuItem(value: items, child: Text(items)); }).toList(), onChanged: (String? newValue) { setState(() { dropDownValue = newValue; }); }, );
内容的提问来源于stack exchange,提问作者editix
相关产品推荐
相关产品推荐

