Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to always display the hint in a DropDownButton?

Tags:

flutter

For example, in a TextField it is possible to set an InputDecoration with a label text, that shows in the center of the TextField when there is no user input, and then shows above the user's input text afterward.

With a DropDownButton I can only seem to get the hint text to display before the user makes a selection, and then it disappears and only displays the user's selection. Is there a way to mimic the TextField's behavior?

Thanks!

like image 328
Haplo Avatar asked Mar 02 '23 15:03

Haplo


1 Answers

You can achieve that using DropDownButtonFormField widget instead of DropDownButton. DropDownButtonFormField has decoration property which lets you use labelText which goes over the top of the field after selecting an item from the list. Sample working code below:

return DropdownButtonFormField<String>(
      decoration: InputDecoration(
        labelText: 'select option'
      ),

      value: selected,
      items: ["A", "B", "C"]
          .map((label) => DropdownMenuItem(
                child: Text(label),
                value: label,
              ))
          .toList(),
      onChanged: (value) {
        setState(() => selected = value);
      },
    );

Output:

enter image description here

enter image description here

Hope this answers your question.

like image 115
Darshan Avatar answered Mar 05 '23 15:03

Darshan