单击下拉菜单项后如何显示自定义值

How to display a custom value after clicking A Drop Down Menu Item

对于 DropDown,当我 select 值显示在下拉列表中的任何特定选项时。

单击特定下拉菜单项后,如何有效地更改显示的内容。

如下图所示。在品牌下拉列表中,一旦我 select 一个项目,它的值就会显示出来。但是,我想更改显示的值。

我该如何做到这一点?谢谢

已编辑请注意提示属性和this.hintValue

您需要在 onChanged 事件中设置 State,并将值关联到像这样从 onchanged 中获取的新值

onChanged: (String newValue) {
    setState(() {
      this.hintValue = newValue;
    });
  },

同时:

 return DropdownButton<String>(
  value: dropdownValue,
  hint: Text("${this.hintValue}"),
  icon: Icon(Icons.arrow_downward),
  iconSize: 24,

完整代码将是这样的:

class DropDownWidget extends StatefulWidget {

  DropDownWidget({Key key}) : super(key: key);

  @override
  _DropDownWidgetState createState() => _DropDownWidgetState();
}

/// This is the private State class that goes with MyStatefulWidget.
class _DropDownWidgetState extends State<DropDownWidget> {
  String dropdownValue = 'One';
  String hintValue;
  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
      value: dropdownValue,
      hint: Text("${this.hintValue}"),
      icon: Icon(Icons.arrow_downward),
      iconSize: 24,
      elevation: 16,
      style: TextStyle(color: Colors.deepPurple),
      underline: Container(
        height: 2,
        color: Colors.deepPurpleAccent,
      ),
      onChanged: (String newValue) {
        setState(() {
          this.hintValue = newValue;
        });
      },
      items: <String>['One', 'Two', 'Free', 'Four']
          .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
  }
}

参考自:flutter docs