首页 > 解决方案 > How to set DropdownButton's value programmatically?

问题描述

For example, in order to set the text in a TextFormField, I can use a TextEditingController:

textEditingController = TextEditingController()
...

TextFormField(
  controller: textEditingController
);
...

textEditingController.text = 'my text'; // This is where I can set the text in the TextFormField

Is there a similar way to programmatically set the selection in a DropdownButton? As far as I know, simply setting the value field in a DropdownButton won't suffice since the change won't be applied without calling the setState from the wrapping state object.

标签: flutter

解决方案


正如@CopsOnRoad 评论的那样,这里似乎没有捷径,setState必须调用才能反映DropdownButton所选值的变化。问题是,setState所以protected我需要通过一些循环来确保在需要时调用它。我最终通过实现一个DropdownButton状态为监听器的通知器来做到这一点。类似于以下内容:

class MyStatefulWidget extends StatefulWidget {

  final _valueNotifier = ValueNotifier<String>(null);

  @override
  State<StatefulWidget> createState() => MyState(_valueNotifier);

  // This exposes the ability to change the DropdownButtons's value
  void setDropdownValue(String value) {
    // This will notify the state and will eventually call setState
    _valueNotifier.value = value;
  }
}

class MyState extends State<MyStatefulWidget> {
  String _selection;

  MyState(ValueNotifier<String> valueNotifier) {
    valueNotifier.addListener(() {
      setState(() {
        _selection = valueNotifier.value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
      items: [
        DropdownMenuItem<String>(
          value: "1",
          child: Text(
            "1",
          ),
        ),
        DropdownMenuItem<String>(
          value: "2",
          child: Text(
            "2",
          ),
        )
      ],
      onChanged: (value) {
        setState(() {
          _selection = value;
        });
      },
      value: _selection,
    );
  }
}

推荐阅读