【问题标题】:Flutter - DropdownButton value stays empty after selectionFlutter - 选择后 DropdownButton 值保持为空
【发布时间】:2019-02-03 14:43:31
【问题描述】:

假设我们在 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 是空的,即使我们点击了一个项目。我们如何解决这个问题?

【问题讨论】:

    标签: flutter spinner dropdownbutton


    【解决方案1】:

    只需创建将存储所选项目的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((){}); },
                ),
          ), 
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-02
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 2020-05-07
      • 2020-04-04
      • 2022-11-03
      • 1970-01-01
      相关资源
      最近更新 更多