繁体   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