簡體   English   中英

Flutter - DropdownButton 值在選擇后保持為空

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM