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((){}); },
),
),
);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.