Flutter DropdownButton: Complete Guide with Examples

Learn Flutter's DropdownButton: show a hint, use enums and objects, style the menu, validate it in a form, and fix the common 'exactly one item' error.

T

Teammity Team

· 4 min read

Dropdowns are everywhere in forms: country, city, category, priority. Flutter's DropdownButton covers all of these, but it has a few rules that trip people up, most famously the "There should be exactly one item with [DropdownButton]'s value" error. This guide covers the basics, styling, forms, and how to avoid that error for good.

Step 1: A basic DropdownButton

A dropdown needs three things: the current value, the list of items, and an onChanged callback that updates the value.

lib/widgets/city_picker.dart
class CityPicker extends StatefulWidget {
  const CityPicker({super.key});
 
  @override
  State<CityPicker> createState() => _CityPickerState();
}
 
class _CityPickerState extends State<CityPicker> {
  static const _cities = ['Mumbai', 'Pune', 'Bengaluru', 'Delhi'];
  String? _selectedCity;
 
  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
      value: _selectedCity,
      hint: const Text('Select a city'),
      items: _cities
          .map((city) => DropdownMenuItem(value: city, child: Text(city)))
          .toList(),
      onChanged: (value) => setState(() => _selectedCity = value),
    );
  }
}

A few things to notice:

  • DropdownButton<String>: the type parameter must match the type of each item's value.
  • _selectedCity starts as null, so the hint is shown until the user picks something.
  • DropdownButton does not remember the selection itself. You store it in state and call setState in onChanged.

Step 2: Use an enum for fixed options

When the options are fixed in code, an enum is safer than strings because typos become compile errors:

enum Priority { low, medium, high }
 
Priority _priority = Priority.medium;
 
DropdownButton<Priority>(
  value: _priority,
  items: Priority.values
      .map((p) => DropdownMenuItem(value: p, child: Text(p.name)))
      .toList(),
  onChanged: (value) {
    if (value != null) setState(() => _priority = value);
  },
)

onChanged always gives you a nullable value, so check for null before assigning it to a non-nullable field.

Step 3: Style the button and the menu

Out of the box, DropdownButton is only as wide as its longest item and has an underline. These properties cover most design needs:

DropdownButton<String>(
  value: _selectedCity,
  isExpanded: true,
  icon: const Icon(Icons.keyboard_arrow_down),
  underline: const SizedBox.shrink(),
  borderRadius: BorderRadius.circular(12),
  dropdownColor: Colors.white,
  menuMaxHeight: 300,
  style: const TextStyle(fontSize: 16, color: Colors.black87),
  items: _cities
      .map((city) => DropdownMenuItem(value: city, child: Text(city)))
      .toList(),
  onChanged: (value) => setState(() => _selectedCity = value),
)
PropertyWhat it does
isExpandedFills the available width and ellipsizes long text.
iconReplaces the default arrow.
underlinePass SizedBox.shrink() to remove the line under the button.
borderRadiusRounds the corners of the open menu.
dropdownColorBackground colour of the open menu.
menuMaxHeightMakes long lists scroll instead of covering the whole screen.

Show something different when closed

selectedItemBuilder lets the closed button look different from the menu items, for example adding a label:

selectedItemBuilder: (context) =>
    _cities.map((city) => Text('City: $city')).toList(),

It must return one widget per item, in the same order as items.

Step 4: Disable the dropdown

Pass null to onChanged to disable it, for example while the options are loading. Use disabledHint to explain why:

DropdownButton<String>(
  value: _selectedCity,
  disabledHint: const Text('Loading cities...'),
  items: _cityItems,
  onChanged: _isLoading ? null : (value) => setState(() => _selectedCity = value),
)

Step 5: Validate it inside a Form

In a form, use DropdownButtonFormField. It adds a label, a border, and validation just like TextFormField:

lib/screens/signup_form.dart
final _formKey = GlobalKey<FormState>();
String? _city;
 
Form(
  key: _formKey,
  child: Column(
    children: [
      DropdownButtonFormField<String>(
        initialValue: _city,
        decoration: const InputDecoration(
          labelText: 'City',
          border: OutlineInputBorder(),
        ),
        items: const ['Mumbai', 'Pune', 'Bengaluru']
            .map((city) => DropdownMenuItem(value: city, child: Text(city)))
            .toList(),
        onChanged: (value) => setState(() => _city = value),
        validator: (value) => value == null ? 'Please select a city' : null,
      ),
      ElevatedButton(
        onPressed: () {
          if (_formKey.currentState!.validate()) {
            // Submit _city
          }
        },
        child: const Text('Submit'),
      ),
    ],
  ),
)

Using objects as values

You can use your own classes as values, but Flutter compares the selected value with each item using ==. By default, two separate objects are never equal, even with the same data. Override == and hashCode:

lib/models/country.dart
class Country {
  const Country(this.code, this.name);
  final String code;
  final String name;
 
  @override
  bool operator ==(Object other) => other is Country && other.code == code;
 
  @override
  int get hashCode => code.hashCode;
}

Without this, reloading the country list from an API creates new objects, your saved selection no longer matches any of them, and you get the error below.

Common mistakes

"There should be exactly one item with [DropdownButton]'s value"

This assertion means value matches zero or more than one of the items. The usual causes:

  • The value is not in the list. For example, value: 'mumbai' when the items contain 'Mumbai', or a saved value from an old list. Make sure value is null or one of the item values.
  • Duplicate items. Two items with the same value. Remove duplicates with .toSet().toList().
  • Objects without ==. See the section above.
  • The list changed but the value did not. When you replace the items (for example, the cities for a new state), reset the selected value to null at the same time.

Other mistakes

  • Text overflow. Long item text overflows a narrow button. Set isExpanded: true.
  • Selection does not change. You forgot setState in onChanged, or you are storing the value in a local variable inside build, which resets on every rebuild.
  • Huge menus. A list of 200 countries fills the screen. Set menuMaxHeight, or use an autocomplete field for very long lists.

Wrapping up

  • Store the selected value in state, update it in onChanged, and use hint for the empty state.
  • Use isExpanded, borderRadius and menuMaxHeight for a polished look, and DropdownButtonFormField for validation.
  • The "exactly one item" error always means value does not match exactly one item. Check for case differences, duplicates and missing ==.

Watch the full walkthrough in the video above, and see more Flutter tutorials.

Keep reading

flutterwidgetsux

How to Add a Search Bar to the AppBar in Flutter

Add an animated search bar with suggestions to your Flutter AppBar using easy_search_bar, filter a list as the user types, and load results from an API.

· 3 min read