Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - DropdownButton value stays empty after selection

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?

like image 230
kosiara - Bartosz Kosarzycki Avatar asked Nov 26 '25 18:11

kosiara - Bartosz Kosarzycki


1 Answers

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((){}); },
            ),
      ), 
    );
  }
}
like image 149
kosiara - Bartosz Kosarzycki Avatar answered Nov 29 '25 10:11

kosiara - Bartosz Kosarzycki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!