sodium
sodium

Reputation: 3

Flutter: Different Text in Field and Dropdown List for DropdownButtonFormField

I am trying to implement a DropdownButtonFormField which should work similarly to a country-code selector. In its dropdown list, the full names and corresponding codes are demonstrated, while when one of them is selected, the form should only keep the country code. Is there any approach to accomplish this?

Alternatively, is there any way to hide the value selected and leave only the dropdown triangle button, so that I can add widgets to display by myself? I tried to put it in a SizedBox with an extremely small width as the solution of the alternating question, but that looks terrible.

Here is a demonstration of what I expected (modifying the DropdownMenu sample but it does not work when the field contains only country code). demonstration

enter image description here

Thanks.

Upvotes: 0

Views: 455

Answers (1)

sodium
sodium

Reputation: 3

This can be finished by implementing the selectedItemBuilder.

For instance, for the country codes defined in enum that

enum EnumOfCountries {
  us('United States', 1),
  fr('France', 33),
  uk('United Kingdom', 44),
  br('Brazil', 55);

  final String name;
  final int code;

  const EnumOfCountries(this.name, this.code);
}

It can be displayed by the following widget:

return Container(
  width: 100,
  child: DropdownButtonFormField(
    // variable for storage of selected item
    value: country,
    // label above the form field
    decoration: InputDecoration(labelText: 'Country Code'),
    // form border
    borderRadius: BorderRadius.all(Radius.circular(8)),
    // while selecting an item, update it to our variable
    // note that the [value] is in type of [EnumOfCountries?]
    onChanged: (value) {
      setState(() {
        country = value ?? country;
      });
    },
    // to configure the style of list of items
    // (also the selected item if selectedItemBuilder is not given)
    items: EnumOfCountries.values.map<DropdownMenuItem<EnumOfCountries>>(
      (e) => DropdownMenuItem<EnumOfCountries>(
        value: e, 
        child: Text('${e.name} (+${e.code.toString()})'),
      )
    ).toList(),
    // to configure the style of selected item in the form field
    selectedItemBuilder: (context) => EnumOfCountries.values.map<Widget>(
      (e) => Text('+${e.code}'),
    ).toList(),
  ),
);

The item can control the style of dropdown list, while the selectedItemBuilder allows to display selected item in another style. So the purpose is accomplished.

Upvotes: 0

Related Questions