我正在实现相应的下拉菜单(第二个下拉菜单的选项取决于第一个下拉菜单),它使用这种格式的对象列表:
List<State> states = [
new State(stateId: 1, stateName: "New York", cities: [
new City(cityId: 1, cityName: "New York City"),
new City(cityId: 2, cityName: "Buffalo") ...
小部件代码是这样的:
children: <Widget>[
DropdownButtonFormField<int>(
decoration: InputDecoration(labelText: 'State'),
value: selectedStateId,
items: states.map((State state) {
return new DropdownMenuItem<int>(
value: state.stateId,
child: new Text(states.singleWhere((x) => x.stateId == state.stateId).stateName),
);
}).toList(),
onChanged: (int newStateId) {
setState(() {
this.selectedCityId = states.singleWhere((x) => x.stateId == newStateId).cities[0].cityId; // set to first city for this state
this.selectedStateId = = newStateId;
});
},
),
DropdownButtonFormField<int>(
decoration: InputDecoration(labelText: 'City'),
value: selectedCityId,
items: states.singleWhere((x) => x.stateId == selectedStateId)
.cities
.map((City city) {
return new DropdownMenuItem<int>(
value: city.cityId,
child: new Text(states
.singleWhere((x) => x.stateId == selectedStateId).cities.singleWhere((x) => x.cityId == city.cityId).cityName),
);
}).toList(),
onChanged: (int newCityId) {
setState(() {
this.selectedCityId = newCityId;
});
},
)
],
当我在此示例中更改状态下拉列表时,我收到一个错误:“应该恰好有一个项目具有 [DropdownButton] 的值:1。检测到零或 2 个或多个 [DropdownMenuItem] 具有相同的值”。
上述错误中的“1”对应于更改状态之前选择的城市值,所以我知道该错误与它仍在寻找旧的 selectedCityId 并且它不再在项目列表中的事实有关,但我不确定为什么我在 setState 中更改了该值。我相信,这个问题的一个关键是,如果我只是将 DropDownButtonFormField 更改为常规 DropDownButtons,那么完全相同的代码就可以工作,但我想使用前者附带的内置标签文本。