3

Suppose we have created a simple DropdownButton ABCPageState in an ABC stateful widget.

class ABCPageState extends State<ABCPage> {

  @override 
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Container(
        child:
          new DropdownButton(
                hint: new Text("Please select value"),
                items: <String>['Value 1', 'Value2'].map((String value) {
                  return new DropdownMenuItem<String>(
                    value: value,
                    child: new Text(value),
                  );
                }).toList(),
                onChanged: (_) {},
          )
      )
    );
  }
}

but NO VALUE is selected after we click on one of the options. In other words - DropdownButton is empty even though we clicked an item. How can we fix that?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

1 Answers1

3

Simply create dropdownSelectedItem variable which will store the selected item. DropdownButton has a value property which sets the selected value. In the onChanged callback - set the value to dropdownSelectedItem variable. Remember to call setState method afterwards to redraw the UI.

class ABCPageState extends State<ABCPage> {

  var dropdownSelectedItem;

  @override 
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Container(
        child:
          new DropdownButton(
                hint: new Text("Please select value"),
                items: <String>['Value 1', 'Value2'].map((String value) {
                  return new DropdownMenuItem<String>(
                    value: value,
                    child: new Text(value),
                  );
                }).toList(),
                value: dropdownSelectedItem,
                onChanged: (val) { dropdownSelectedItem = val; setState((){}); },
            ),
      ), 
    );
  }
}