颤振中的下拉按钮不会将值切换到所选值

Dar*_*adi 9 dart flutter flutter-layout

我最近开始使用飞镖和颤振进行编程,尽管我最近想添加下拉菜单为用户提供多种选择,但我的应用程序运行一直很顺利。一切都按计划进行,但是当我从列表中选择一个值时,它不会更改框中的值,而是返回到提示或一个空框。任何帮助,将不胜感激!

这是我的下拉按钮代码:

Widget buildDropdownButton() {
String newValue;

return new Padding(
  padding: const EdgeInsets.all(24.0),
  child: new Column(
    mainAxisAlignment: MainAxisAlignment.start,
    children: <Widget>[
      new ListTile(
        title: const Text('Frosting'),
        trailing: new DropdownButton<String>(
            hint: Text('Choose'),
            onChanged: (String changedValue) {
              newValue=changedValue;
              setState(() {
                newValue;
                print(newValue);
              });
            },
            value: newValue,
            items: <String>['None', 'Chocolate', 'Vanilla', 'ButterCream']
                .map((String value) {
              return new DropdownMenuItem<String>(
                value: value,
                child: new Text(value),
              );
            }).toList()),
      ),
    ],
  ),
);
}
Run Code Online (Sandbox Code Playgroud)

Lal*_*dar 15

面临同样的问题,但没有一个答案有效。然后,我在我的一个旧项目中找到了解决方案。

我在这里使用它AlertDialog

所以,更改DropdownButtonDropdownButtonFormField

并添加onSaved完全如下onChanged

onSaved: (value) {
    setState(() {
        _selectedValue = value;
    });
}
Run Code Online (Sandbox Code Playgroud)

就是这样。它将开始工作。

  • 这是唯一对我有用的解决方案,谢谢拉利特,即使使用 onChange,它也能在将 DropdownButton 更改为 DropdownButtonFormField 后起作用 (2认同)

die*_*per 14

该错误是因为您在声明一个方法变量newValue时必须在变量内部将该变量声明为全局变量StatefulWidget

   String newValue;

  Widget buildDropdownButton() {
  return new Padding(
    padding: const EdgeInsets.all(24.0),
    child: new Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        new ListTile(
          title: const Text('Frosting'),
          trailing: new DropdownButton<String>(
              hint: Text('Choose'),
              onChanged: (String changedValue) {
                newValue=changedValue;
                setState(() {
                  newValue;
                  print(newValue);
                });
              },
              value: newValue,
              items: <String>['None', 'Chocolate', 'Vanilla', 'ButterCream']
                  .map((String value) {
                return new DropdownMenuItem<String>(
                  value: value,
                  child: new Text(value),
                );
              }).toList()),
        ),
      ],
    ),
  );
  }
Run Code Online (Sandbox Code Playgroud)