![](/img/trans.png)
[英]How to resolve flutter dropdownButtonFormField dynamic selection checking for dropdownButton's value
[英]Flutter - DropdownButton value stays empty after selection
假設我們在 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: (_) {},
)
)
);
}
}
但是在我們單擊其中一個選項后選擇了 NO VALUE 。 換句話說 - 即使我們點擊了一個項目,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((){}); },
),
),
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.