我创建了一个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(位于脚手架内),其中装有我要按下以重置Dropdown的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

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

  • 另外,您可以使用Flutter本身使用的 Controller 模式。例如TextField具有TextEditingController:https://docs.flutter.io/flutter/widgets/TextEditingController-class.html

    关于dart - 从State类外部更改Flutter小部件的状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49485375/

    10-09 10:15