在我的代码中,添加了一个如下所示的下拉列表,当我在下拉列表中切换选择时,其未更新其显示异常,我在statefull小部件中声明了一个变量,在我的下拉函数中,我将其分配为A值,下拉按钮,在Onchanged中,我将json传递给另一个函数,我从变量中获取值并将其分配给setState中的opSelected变量
class _ReportFilterState extends State<ReportFilter> {
String opSelected;
//declared string to hold the selected value in dropdown within the state class.
buildMainDropdown(List<Map<String, Object>> items, StateSetter setState) {
return Container(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 27.0,
vertical: 16.0,
),
child: Align(
alignment: Alignment.topLeft,
child: DropdownButtonHideUnderline(
child: DropdownButton(
isExpanded: true,
hint: Text("Choose Filters"),
value: opSelected, // Here assigning the value
items: items
.map((json) => DropdownMenuItem(
child: Text(json["displayName"]), value: json))
.toList(),
onChanged: (json) {
manageIntState(json, setState);
},
),
),
),
),
);
}
void manageIntState(Map<String, Object> jsonSelected, StateSetter setState) {
setState(() {
dispName = jsonSelected["displayName"];
//here I am setting the selected value
opSelected = dispName;
//Doing some operations
id = jsonSelected['id'];
type = jsonSelected['type'];
selectedFilterOption = jsonSelected;
if (jsonSelected.containsKey("data")) {
List<Map<String, Object>> tempList;
List<String> dailogContent = List<String>();
tempList = jsonSelected['data'];
tempList
.map((val) => {
dailogContent.add(val['displayId']),
})
.toList();
_showReportDialog(dailogContent);
}
});
}
但是当我跑步时,我将出现错误
item == null ||items.isEmpty || value == null || itsems.where(((DropdownMenuItemitem)=> item.value == value).length == 1不正确..
让我知道我在代码中做错了什么,所以如果我评论它未显示所选的下拉值,它就会给我这样的信息。
value
的所选DropdownButton
不是其项目的值之一时,就会发生该错误。在您的情况下,您的项目值为json
,即Map<String, Object>
,而DropdownButton
的值是opSelected
,即String
。
所以您需要像这样更改opSelected
的类型:
Map<String, Object> opSelected;
还请确保将对相同项目列表的引用传递给buildMainDropdown()
,因为如果在调用buildMainDropdown()
时创建新列表,则DropdownButton
将具有选项的另一个引用,这是不允许的] >[Note:
您可能希望对地图使用动态而不是对象,例如:Map<String, dynamic> opSelected;
这是原因:What is the difference between dynamic and Object in dart?