flutter - 如何在调用 setState 时强制颤振重建特定的小部件
问题描述
我有一stateful widget
堂课。它的 build 方法中有一个 listView。在列表视图中,我有两个dropDownButtonFormField
. 最初,仅显示第一个下拉菜单。在 to 中选择一个值后,通过调用set state
. 第二个下拉按钮取决于第一个按钮的选择。
现在代码工作正常。在第一个下拉按钮中选择值后,将出现第二个下拉按钮,其中包含与第一个选择的值相对应的选项。But error occurs when a an option from the second button is selected and first button's option is changed.
每次更改第一个下拉列表的选定选项时,如何强制颤振重绘第二个下拉列表?
这是运行和崩溃的应用程序:
代码:
//called inside the list view childrens list
Widget showLocationDropDown() {
return Padding(
padding: const EdgeInsets.fromLTRB(0.0, 20.0, 0.0, 0.0),
child: Container(
child: Column(
children: <Widget>[
_getProvinceDropDown(),
_selectedProvince == null ? Container(): _getCityDropDown(),
],
),
),
);
}
Widget _getCityDropDown() {
return Column(
children: <Widget>[
Container(
height: 20,
),
Row(
children: <Widget>[
Icon(Icons.location_city, color: Colors.grey),
Container(
width: 17.0,
),
Expanded(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButtonFormField(
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(color: Colors.grey))),
hint: Text('Please choose your city'),
value: _selectedCity,
onChanged: (newValue) {
setState(() {
_selectedCity = newValue;
});
},
items: _getCities().map((location) {
return DropdownMenuItem(
child: Text(location),
value: location,
);
}).toList(),
),
),
),
],
),
],
);
}
List<String> _getCities() {
switch (_selectedProvince) {
case ("Sindh"):
return _sindhCities;
case ("Punjab"):
return _punjabCities;
case ("Balouchistan"):
return _balouchCities;
case ("KPK"):
return _kpkCities;
}
List<String> deflt = ['Please Select Province'];
return deflt;
}
Widget _getProvinceDropDown() {
return Row(
children: <Widget>[
Icon(Icons.map, color: Colors.grey),
Container(
width: 17.0,
),
Expanded(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButtonFormField(
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(color: Colors.grey),
),
),
hint: Text('Please choose your province'),
value: _selectedProvince,
onChanged: (newValue) {
setState(() {
_selectedProvince = newValue;
_selectedCity = null;
stateChange = !stateChange;
});
},
items: _province.map((province) {
return DropdownMenuItem(
child: Text(province),
value: province,
);
}).toList(),
),
),
),
],
);
}
解决方案
而不是 _selectedCity = null,尝试 _selectedCity = _getCities().first;
推荐阅读
- javascript - Javascript - LocalStorage 不适合我
- c++ - 是否有使用c ++中的三角分布生成随机数的函数?
- python - 如何从 python 的第一行重新运行代码?
- python - 如何在不收到错误消息的情况下将函数调用到另一个代码文件中;以及如何将字典与列表进行比较?
- python - 具有单个 TTL 的过期字典
- css - 溢出:隐藏在某个位置:固定 div
- python-3.x - 为什么 Python 会随机执行函数?
- java - 在这种情况下如何正确使用 Getter
- rubygems - 如何使用 Shoryuken 获得工作统计数据?
- javascript - 如何创建一个选择另一个对象并在浏览器中刷新的函数