gpt4 book ai didi

flutter - Flutter:应该只有[DropdownButton]值的一项

转载 作者:行者123 更新时间:2023-12-03 02:38:50 25 4
gpt4 key购买 nike

我正在尝试在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 || value == null ||



因此崩溃:

crash_message

解决方案使用一些默认值初始化value对象。 请注意值应为集合中包含的值之一。 如果不是,则可能会导致崩溃。
  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

关于flutter - Flutter:应该只有[DropdownButton]值的一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60510150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com