【发布时间】:2018-03-26 06:40:43
【问题描述】:
我创建了一个 DropdownButton 作为 StatefulWidget。该类称为 MyDropDown,对应的状态称为 MyDropDownState。
我在 MyDropDownState 类中创建了一个重置函数:
void reset(){
setState((){
_selection = null;
});
}
这会将选择设置为 null 并设置下拉菜单的状态,从而有效地重置下拉菜单。
问题的核心是我必须在 AppBar 上的 IconButton 被按下时调用这个函数。我尝试了多种方法,但无法访问我创建的 MyDropDown 类的状态。
这是 MyDropDown 的代码和它的状态,简化:
class MyDropDown extends StatefulWidget {
final Map<String, String> _itemMap;
MyDropDown(this._itemMap);
@override
MyDropDownState createState() => new MyDropDownState();
}
class MyDropDownState extends State<MyDropDown> {
String _selection;
void reset(){
setState((){
_selection = null;
});
}
@override
void initState() {
_selection = null;
super.initState();
}
@override
Widget build(BuildContext context) {
return new DropdownButton(
value: _selection,
//getDropItems builds dropdown items
items: getDropItems(widget._itemMap),
onChanged: (s) {
setState(() {
_selection = s;
});
},
);
}
}
在我的主页中,我创建了一个新的 MyDropDown
final MyDropDown cityDropdown = new MyDropDown(cityLookup);
那么这是 AppBar(在 Scaffold 内),它包含我想要按下以重置下拉菜单的 IconButton。
appBar : new AppBar(
title: new Text('Filter Jobs'),
actions: <Widget>[
new IconButton(
icon: new Icon(Icons.refresh),
onPressed: () {
print('Reset dropdowns');
//this is where I would call reset() on cityDropdown's state, if I could figure out how to get to it :/
},
),
],
),
【问题讨论】: