Change state of Flutter widget from outside it'

2020-07-03 04:10发布

问题:

I created a DropdownButton as a StatefulWidget. The class is called MyDropDown, with the corresponding state called MyDropDownState.

I created a reset function in the MyDropDownState class:

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

which will set the selection to null and set the state of the dropdown, effectively resetting the dropdown.

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.

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;
            });
          },
      );
  }

}

In my main page, I create a new MyDropDown

final MyDropDown cityDropdown = new MyDropDown(cityLookup);

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 :/
          },
      ),
    ],
  ),

回答1:

The simplest solution here would be to use a GlobalKey<T>: https://docs.flutter.io/flutter/widgets/GlobalKey-class.html

  1. Create GlobalKey<MyDropDownState> in your page widget and pass it to the MyDropDown.
  2. Use that key in your callback: key.currentState.reset();

Alternatively, you can use controller pattern that Flutter itself uses. For example TextField has TextEditingController: https://docs.flutter.io/flutter/widgets/TextEditingController-class.html



标签: dart flutter