从State类外部更改Flutter小部件的状态 [英] Change state of Flutter widget from outside it's State class
问题描述
我创建了一个DropdownButton作为StatefulWidget。该类称为MyDropDown,相应的状态称为MyDropDownState。
I created a DropdownButton as a StatefulWidget. The class is called MyDropDown, with the corresponding state called MyDropDownState.
我在MyDropDownState类中创建了一个重置函数:
I created a reset function in the MyDropDownState class:
void reset(){
setState((){
_selection = null;
});
}
这将有效地将选择设置为null并设置下拉菜单的状态重置下拉列表。
which will set the selection to null and set the state of the dropdown, effectively resetting the dropdown.
问题的核心是我必须在按下AppBar上的IconButton时调用此函数。我尝试了多种方法,只是无法访问我创建的MyDropDown类的状态。
The core of the problem is I have to call this function when an IconButton on the AppBar is pressed. I have tried multiple ways and just can't get access to the state of the MyDropDown class I created.
这是MyDropDown的代码,它的状态为简体: / p>
This is the code of MyDropDown and it's State, simplified:
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
In my main page, I create a new MyDropDown
final MyDropDown cityDropdown = new MyDropDown(cityLookup);
然后这是AppBar(在脚手架内),其中装有我要按下以重置图标的IconButton
then this is the AppBar (inside a Scaffold) that holds the IconButton I want to press to reset the 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
The simplest solution here would be to use a GlobalKey<T>
: https://docs.flutter.io/flutter/widgets/GlobalKey-class.html
- 创建
GlobalKey< MyDropDownState>
并将其传递给MyDropDown。 - 在回调中使用该键:
key.currentState.reset()
;
- Create
GlobalKey<MyDropDownState>
in your page widget and pass it to the MyDropDown. - Use that key in your callback:
key.currentState.reset()
;
或者,您可以使用Flutter本身使用的控制器模式。例如, TextField
具有 TextEditingController
: https://docs.flutter.io/flutter/widgets/TextEditingController-class.html
Alternatively, you can use controller pattern that Flutter itself uses. For example TextField
has TextEditingController
: https://docs.flutter.io/flutter/widgets/TextEditingController-class.html
这篇关于从State类外部更改Flutter小部件的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!