A Detailed Guide to the Flutter Dropdown Widget

Parth ShethParth Sheth
6 min read

In Flutter, creating a dropdown menu is an essential part of many user interfaces. Dropdowns allow users to select an option from a list, and they're widely used for selecting items from predefined lists, filtering options, and settings selection. Flutter provides a DropdownButton widget to handle this functionality with ease.

What is the DropdownButton Widget?

The DropdownButton widget in Flutter is a Material Design widget that allows users to select a single item from a list of items. It displays the currently selected item and a button that opens a menu of other options when tapped.

Basic Example

DropdownButton<String>(
  value: selectedValue,
  onChanged: (String? newValue) {
    setState(() {
      selectedValue = newValue!;
    });
  },
  items: <String>['One', 'Two', 'Three', 'Four']
      .map<DropdownMenuItem<String>>((String value) {
    return DropdownMenuItem<String>(
      value: value,
      child: Text(value),
    );
  }).toList(),
)

Properties of DropdownButton

Let's break down the key properties of the DropdownButton widget and explore how to use them.

1. value

The value property holds the current selected value in the dropdown. This is typically a variable in your state, which represents the selected item. The DropdownButton will display the item corresponding to this value.

  • Type: T? (nullable type, meaning it can be null initially).

  • Required? Yes.

String? selectedValue = 'One';

2. onChanged

The onChanged property is a callback function that is triggered when the user selects an item from the dropdown. The function receives the new value as a parameter, allowing you to update the selected value.

  • Type: ValueChanged<T?>? (a function that takes the selected value as a parameter).

  • Required? Yes (but can be null if the dropdown is disabled).

Example:

onChanged: (String? newValue) {
  setState(() {
    selectedValue = newValue!;
  });
}

If you want to disable the dropdown, simply set onChanged to null:

onChanged: null, // Disables the dropdown

3. items

The items property is a list of DropdownMenuItem widgets that define the options the user can select from. Each DropdownMenuItem contains a value and a child widget (usually a Text widget).

  • Type: List<DropdownMenuItem<T>>

  • Required? Yes.

Example:

items: <String>['One', 'Two', 'Three']
    .map<DropdownMenuItem<String>>((String value) {
  return DropdownMenuItem<String>(
    value: value,
    child: Text(value),
  );
}).toList(),

Here, we map each value to a DropdownMenuItem, which is required to provide both a value (the actual data) and a child (a widget to display).

4. hint

The hint property is displayed when no item has been selected yet. It’s often used for guiding the user or showing a placeholder text like "Select an option".

  • Type: Widget?

  • Required? No.

Example:

hint: Text('Select a number'),

5. icon

The icon property defines the widget that appears as the dropdown’s indicator (the little arrow). By default, this is an arrow pointing down, but you can customize it with any widget you like.

  • Type: Widget

  • Required? No.

Example:

icon: Icon(Icons.arrow_drop_down),

You can change this to any icon or even a custom widget.

6. isExpanded

The isExpanded property determines whether the dropdown should expand to take up the full width of the parent container. By default, the dropdown will only take up as much space as its content. Setting isExpanded: true will make the dropdown take up the full width of its parent widget.

  • Type: bool

  • Required? No.

Example:

isExpanded: true, // Ensures the dropdown takes up the full width

7. underline

The underline property controls the appearance of the line below the dropdown button. By default, a thin line is shown under the dropdown button, but you can customize this or remove it by setting this property to a different widget.

  • Type: Widget

  • Required? No.

Example:

underline: Container(), // Removes the underline

You can also customize the underline to create a styled border.

8. style

The style property is used to define the text style of the selected value displayed in the dropdown button. This is a TextStyle widget, where you can set properties like font size, color, weight, etc.

  • Type: TextStyle?

  • Required? No.

Example:

style: TextStyle(color: Colors.blue, fontSize: 18),

9. dropdownColor

The dropdownColor property allows you to change the background color of the dropdown menu when it is opened. This can be useful for visual distinction between the dropdown and the rest of the UI.

  • Type: Color?

  • Required? No.

Example:

dropdownColor: Colors.yellow,

10. elevation

The elevation property controls how "raised" the dropdown menu looks. A higher value will make the dropdown appear more raised, while a lower value will make it flatter. This is essentially a shadow effect.

  • Type: double?

  • Required? No.

Example:

elevation: 8.0, // Adds shadow to the dropdown

11. isDense

The isDense property helps to reduce the vertical space in the dropdown. When set to true, it makes the dropdown items appear closer together, which can be useful for compact UIs.

  • Type: bool

  • Required? No.

Example:

isDense: true, // Reduces the vertical space between items

12. focusColor

The focusColor property changes the color of the dropdown button when it is focused, such as when it is tapped or clicked.

  • Type: Color?

  • Required? No.

Example:

focusColor: Colors.green,

Complete Example

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DropdownExample(),
    );
  }
}

class DropdownExample extends StatefulWidget {
  @override
  _DropdownExampleState createState() => _DropdownExampleState();
}

class _DropdownExampleState extends State<DropdownExample> {
  String? selectedValue = 'One';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Flutter Dropdown Example')),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            DropdownButton<String>(
              value: selectedValue,
              onChanged: (String? newValue) {
                setState(() {
                  selectedValue = newValue;
                });
              },
              items: <String>['One', 'Two', 'Three', 'Four']
                  .map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
              hint: Text('Select an option'),
              icon: Icon(Icons.arrow_drop_down),
              isExpanded: true,
              style: TextStyle(color: Colors.blue, fontSize: 18),
              dropdownColor: Colors.yellow,
              elevation: 8.0,
              isDense: true,
            ),
          ],
        ),
      ),
    );
  }
}

Conclusion

The DropdownButton widget in Flutter is a powerful and flexible tool for displaying a list of items for selection. It allows for various customizations such as changing the icon, the background color, adding a hint, and much more. By understanding these properties, you can easily build dropdown menus that fit the design requirements of your app.

To sum up, here’s a quick recap of the key properties:

  • value: The currently selected item.

  • onChanged: The callback that handles selection changes.

  • items: The list of options to display.

  • hint: A placeholder text shown when nothing is selected.

  • icon: The indicator icon for the dropdown.

  • isExpanded: Controls whether the dropdown takes full width.

  • underline: Customizes the line under the dropdown button.

  • style: Styles the selected item text.

  • dropdownColor: Customizes the background color of the dropdown menu.

  • elevation: Controls the shadow under the dropdown menu.

  • isDense: Reduces the vertical space between items.

With these properties in hand, you should be able to create dynamic and user-friendly dropdowns in your Flutter applications.

Happy coding 😊

0
Subscribe to my newsletter

Read articles from Parth Sheth directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Parth Sheth
Parth Sheth

"🚀 Fluttering through the digital cosmos, I am Parth Sheth, a passionate architect of interactive marvels in the realm of Flutter development. With a fervent love for coding and an insatiable curiosity for the ever-evolving tech landscape, I embark on a perpetual quest to redefine the boundaries of innovation. From sleek UI designs to seamless user experiences, I orchestrate symphonies of code that resonate with elegance and functionality. 💻✨ My journey in Flutter is more than just a profession; it's a thrilling odyssey where creativity meets craftsmanship. Armed with a keen eye for detail and an arsenal of cutting-edge tools, I navigate the complexities of app development with finesse, crafting solutions that not only meet but exceed expectations. 🎨🔧 But beyond the lines of code lies a deeper commitment—to inspire, empower, and elevate. Through my words, my work, and my unwavering dedication to excellence, I strive to ignite the spark of imagination in others, fostering a community where innovation knows no bounds. 🌟💡 So come, fellow adventurers, and join me on this exhilarating expedition into the unknown. Together, let's sculpt the future, one pixel at a time, and unleash the full potential of Flutter's boundless possibilities. Connect with me, and let's embark on this extraordinary voyage—together, we shall chart new horizons and redefine what's possible in the digital landscape. 🌍🔍"