Flutter - 选择后 DropdownButton 值保持为空

标签 flutter spinner dropdownbutton

假设我们在 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/

相关文章:

Flutter:关闭深色模式主题

android - Flutter重新运行内部StatefulWidget的initState函数

flutter - 如何在 flutter 中为 RichText 小部件的 maxlines 属性设置动画

dart - DropDownButton 所选项目在 UI 中未更改

dart - 包含项目 : within Flutter DropdownButton, 的 map 中的返回语句 为什么以及如何工作

android - 如何在 Flutter 中格式化日期时间

单击 BadTokenException 时出现 Android Spinner 异常

jquery - 页面加载时显示加载微调器

android - ActivityGroup 子项中的微调器不起作用

flutter - InputDecoration errorText 必须是常量