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?
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((){}); },
),
),
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With