【问题标题】:How to display a custom value after clicking A Drop Down Menu Item单击下拉菜单项后如何显示自定义值
【发布时间】:2020-10-10 15:22:07
【问题描述】:

对于下拉菜单,当我选择任何特定选项时,该值会显示在下拉菜单中。

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

您可以从下面的图片中看到。在品牌下拉列表中,一旦我选择了一个项目,它的值就会显示出来。但是,我想更改显示的值。

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

【问题讨论】:

    标签: flutter dart dropdown


    【解决方案1】:

    已编辑,请注意 hint 属性和 this.hintValue

    您需要在 onChanged 事件中设置状态并将值关联到从 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

    【讨论】:

    • 谢谢,但这也会改变下拉列表中的值,不是吗?我只想在占位符中替换值,但在下拉列表中它应该按原样显示。
    • 对不起,我有点误解你的问题,我已经更新了答案,请注意hint属性和this.hintValue
    猜你喜欢
    • 2019-01-10
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    相关资源
    最近更新 更多