Search code examples
flutterdartdropdown

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


For a DropDown when I select any purticular option that value gets displayed in the dropDown.

How do I effectively change what is displayed once a purticular drop down menu item is clicked on.

As you can see from the below images. In the Brands Dropdown once I select an item its value gets displayed. However, I would like to change the value that is displayed.

How do I accomplish that? Thanks.

enter image description here enter image description here


Solution

  • EDITED please pay attention on hint property and this.hintValue

    You need to set State in onChanged event and associate value to new value grabbed from onchanged like this

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

    while:

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

    fullcode will be like this:

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

    reference from: flutter docs