dart – 从它的State类外部更改Flutter小部件的状态
我创建了一个DropdownButton作为StatefulWidget.该类称为MyDropDown,具有名为MyDropDownState的相应状态.
我在MyDropDownState类中创建了一个reset函数: 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(在一个脚手架内),它持有我要按下的IconButton来重置Dropdown. 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 :/ },),], 解决方法
这里最简单的解决方案是使用GlobalKey< T>:
https://docs.flutter.io/flutter/widgets/GlobalKey-class.html
>创建GlobalKey< MyDropDownState>在您的页面窗口小部件中,并将其传递给MyDropDown. 或者,您可以使用Flutter自己使用的控制器模式.例如,TextField具有TextEditingController:https://docs.flutter.io/flutter/widgets/TextEditingController-class.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |