Drop down button in flutter not switching values t

2019-05-23 21:01发布

I've recently started programming using dart and flutter and everything has been going smoothly for my app, although recently i wanted to add drop down menu to provide the user with multiple options to pick from. everything worked as planned however when i pick a value from the list it doesn't change the value in the box, it goes back to the hint or an empty box. any help would be appreciated!

here is my code for the dropdownbutton:

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()),
      ),
    ],
  ),
);
}

1条回答
放荡不羁爱自由
2楼-- · 2019-05-23 21:39

The error is because you are declaring a method variable newValue you must declare that variable as global inside your 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()),
        ),
      ],
    ),
  );
  }
查看更多
登录 后发表回答