假设我们在 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: (_) {},
)
)
);
}
}
但在我们单击其中一个选项后,未选择任何值。换句话说 - 即使我们点击了一个项目,DropdownButton 还是空的。我们如何解决这个问题?
最佳答案
只需创建 dropdownSelectedItem
变量即可存储所选项目。 DropdownButton
有一个 value
属性,用于设置所选值。在 onChanged
回调中 - 将值设置为 dropdownSelectedItem
变量。记得调用 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((){}); },
),
),
);
}
}
关于Flutter - 选择后 DropdownButton 值保持为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52066785/