从 State 外部更改 Flutter 小部件的状态 class

Change state of Flutter widget from outside it's State class

我创建了一个 DropdownButton 作为 StatefulWidget。 class 称为 MyDropDown,相应的状态称为 MyDropDownState。

我在 MyDropDownState 中创建了一个重置​​函数 class:

void reset(){
    setState((){
        _selection = null;
    });
}

这会将选择设置为空并设置下拉列表的状态,从而有效地重置下拉列表。

问题的核心是我必须在按下 AppBar 上的 IconButton 时调用此函数。我尝试了多种方法,但无法访问我创建的 MyDropDown class 的状态。

这是 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。

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

  1. 在页面小部件中创建 GlobalKey<MyDropDownState> 并将其传递给 MyDropDown。
  2. 在回调中使用该键:key.currentState.reset()

或者,您可以使用 Flutter 本身使用的控制器模式。例如 TextFieldTextEditingController: https://docs.flutter.io/flutter/widgets/TextEditingController-class.html