【问题标题】:Change state of Flutter widget from outside it's State class从状态类外部更改 Flutter 小部件的状态
【发布时间】: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 :/
          },
      ),
    ],
  ),

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    这里最简单的解决方案是使用GlobalKey&lt;T&gt;:https://docs.flutter.io/flutter/widgets/GlobalKey-class.html

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

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

    【讨论】:

    • 这很奇怪。我用 GlobalKey 重新创建了你的代码,它运行良好。
    猜你喜欢
    • 2018-09-01
    • 2021-05-28
    • 2021-05-19
    • 2020-10-28
    • 2021-06-17
    • 2019-10-06
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    相关资源
    最近更新 更多