Flutter:应该只有[DropdownButton]值的一项
问题内容:
我正在尝试在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 来 从数据库中获得我的列表 。
问题答案:
好吧,因为没有问题有完全相同的解决方案。我的代码也面临同样的问题。这是我如何解决此问题。
我的DropdownButton的代码:
DropdownButton(
items: _salutations
.map((String item) =>
DropdownMenuItem<String>(child: Text(item), value: item))
.toList(),
onChanged: (String value) {
setState(() {
print("previous ${this._salutation}");
print("selected $value");
this._salutation = value;
});
},
value: _salutation,
),
错误
在下面的代码片段中,我正在设置选择类型为String的状态。现在我的代码有问题是此选择值的默认初始化。最初,我将变量初始化_salutation
为:
String _salutation = ""; //Notice the empty String.
这是一个错误!
初始选择不应为null或为空,因为正确地提到了错误消息。
‘items == null || items.isEmpty || 值== null ||
因此崩溃:
解决方案
使用一些默认值初始化值对象。 请注意 ,该 值应该是您的集合所包含的值之一。 如果不是,则可能会导致崩溃。
String _salutation = "Mr."; //This is the selection value. It is also present in my array.
final _salutations = ["Mr.", "Mrs.", "Master", "Mistress"];//This is the array for dropdown