【发布时间】:2020-06-16 00:09:33
【问题描述】:
我正在尝试在 Flutter 中创建一个下拉按钮。我从我的数据库中获得一个列表,然后我将列表传递给我的dropdownButton一切正常数据按预期显示,但当我从它我得到这个错误:
There should be exactly one item with [DropdownButton]'s value: Instance of 'Tag'.
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 805 pos 15: 'items == null || items.isEmpty || value == null ||
items.where((DropdownMenuItem<T> item) {
return item.value == value;
}).length == 1'
我尝试将 DropdownButton 值设置为 null 它可以工作,但是我看不到所选元素。
这是我的代码:
FutureBuilder<List<Tag>>(
future: _tagDatabaseHelper.getTagList(),
builder: (BuildContext context, AsyncSnapshot<List<Tag>> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView(
children: <Widget>[
SizedBox(
height: MediaQuery.of(context).size.height * 0.2,
),
Container(
margin: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width * 0.07),
child: Theme(
data: ThemeData(canvasColor: Color(0xFF525A71)),
child: DropdownButton<Tag>(
value: _selectedTag,
isExpanded: true,
icon: Icon(
Icons.arrow_drop_down,
size: 24,
),
hint: Text(
"Select tags",
style: TextStyle(color: Color(0xFF9F9F9F)),
),
onChanged: (value) {
setState(() {
_selectedTag = value;
});
},
items: snapshot.data.map((Tag tag) {
return DropdownMenuItem<Tag>(
value: tag,
child: Text(
tag.tagTitle,
style: TextStyle(color: Colors.white),
),
);
}).toList(),
value: _selectedTag,
),
),
),
我使用 futureBuilder 来从数据库中获取我的列表。
【问题讨论】:
-
你试过硬编码一个值吗?字符串值 = "一些值";在您的 FutureBuilder 之前并将其分配给 _value = value;
-
@van 是的,同样的问题。
-
只是补充一下其他人已经提到的,不仅默认值需要匹配列表中的一个值,如果是字符串,大小写也必须匹配。如果您的列表中有 NIGERIA,并且这是默认值,则默认值也必须是 NIGERIA,而不是尼日利亚。
标签: flutter dart drop-down-menu dropdownbutton flutter-futurebuilder