[英]Flutter - DropdownButton value stays empty after selection
Suppose we have created a simple DropdownButton ABCPageState
in an ABC stateful widget.假设我们在 ABC 有状态小部件中创建了一个简单的 DropdownButton
ABCPageState
。
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.但是在我们单击其中一个选项后选择了 NO VALUE 。 In other words - DropdownButton is empty even though we clicked an item.
换句话说 - 即使我们点击了一个项目,DropdownButton 也是空的。 How can we fix that?
我们怎样才能解决这个问题?
Simply create dropdownSelectedItem
variable which will store the selected item.只需创建将存储所选项目的
dropdownSelectedItem
变量。 DropdownButton
has a value
property which sets the selected value. DropdownButton
有一个value
属性,用于设置选定的值。 In the onChanged
callback - set the value to dropdownSelectedItem
variable.在
onChanged
回调中 - 将值设置为dropdownSelectedItem
变量。 Remember to call setState
method afterwards to redraw the UI.记得之后调用
setState
方法来重绘 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((){}); },
),
),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.