How to implement DropDownButton in Flutter

In this article, we will discuss how to implement a DropDownButton in a flutter. What shall we do today is to show two dropdown buttons i.e the First one we use is DropdownButtonFormField which is used in the Form Widget and the Second one is DropdownButton which is for the normal dropdown button. At first, we should know what is DropDownButton in flutter is.

The DropDownButton is a widget that we can use to select one unique value from a set of values. It lets the user select one value from a number of items. The default value shows the currently selected value. We can even include a down arrow icon on the list. On clicking the DropDownButton it opens a list list of items, from which the user can select the desired option. We use the Dropdown Button to display any Dropdown List item as we can change its style according to it. Such as its background color, border secular, etc. This Dropdown list is a clickable widget. Which shows the list of items we have selected. The Dropdown Button has DropDownMenuItem. We initialize whatever is to be shown in the list. and the Dropdown button has a function named onChnaged. When a user clicks on an item from the dropdown. So it triggers and executes the triggered function.

Also read: Date And Time Picker In Flutter

Properties of DropDownButton

items define various items that are to be defined in our dropdown menu/list. a list of items that users can select
valueValue is the currently selected item.
style to style our text in the dropdown menu/list like color, fontsize, fontweight, etc.
alignment how the hint or selected item is positioned within the button.
elevationto elevate the dropdown menu/list.
icon to display an icon on the dropdown button.
iconSize to define the size of the icon.
iconDisabledColor to set icon color when the dropdown button is disabled.
iconEnabledColor to set icon color when the dropdown button is enabled.
dropdownColorto display the background color of the dropdown.
isDense reduces the height of the button.
isExpanded to expand the dropdown button to full width.
selectedItemBuilderWhen the user selects an option from the dropdown list it displays the option on the button. If we want to display some other text instead of the selected option on the button we will use selectedItemBuilder.
hint We can display one of the options from the dropdown list on the button or we can set our desired text by default using the hint.
disabledHintThis property is used to display desired text when the dropdown button is disabled.

Let’s take an example of how we can implement the DropDownButton in our flutter application.

we will create a new model name MenuItem that includes the String of text and IconData for displaying the icon as well as for displaying the remaining space for color and storing it into a new file inside the lib folder name menu_item.dart.

import 'package:flutter/cupertino.dart';

class MenuItem {
  final String text;
  final IconData icon;
  final Color menuColors;

  const MenuItem(
      {required this.text,
       required this.icon,
       required this.menuColors,});
}

Now we will again create a new file name as menu_item_data.dart that includes the dummy data.

import 'package:flutter/material.dart';
import 'package:vlogpost/model/menu_item.dart';

class MenuItems {
  static const List<MenuItem> itemMenu = [
    menuSettings,
    menuCheck,
    menuRate,
  ];
  static const menuSettings = MenuItem(
    text: 'Settings',
    icon: Icons.settings,
    menuColors: Colors.amber,
  );
  static const menuRate = MenuItem(
    text: 'Rate',
    icon: Icons.star,
    menuColors: Colors.blueAccent,
  );
  static const menuCheck = MenuItem(
    text: 'Check Out',
    icon: Icons.shopping_basket,
    menuColors: Colors.green,
  );
}

Now let’s implement the code in the Flutter application. The final code looks like this:

import 'package:flutter/material.dart';
import 'package:vlogpost/data/menu_item_data.dart';
import 'package:vlogpost/model/menu_item.dart';

class DropDownScreen extends StatefulWidget {
  const DropDownScreen({Key? key}) : super(key: key);

  @override
  State<DropDownScreen> createState() => _DropDownScreenState();
}

class _DropDownScreenState extends State<DropDownScreen> {
  List<String> item = [
    'Apple',
    'Banana',
    'Mango',
    'Orange',
    'Grape',
  ];

  List<MenuItem> menuItems = [];
  @override
  void initState() {
    menuItems = List.of(MenuItems.itemMenu);
    super.initState();
  }

  String dropdown = 'Apple';
  MenuItem dropdownValue = MenuItems.itemMenu.first;
  final _dropdownFormKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('DropDown Button in Flutter'),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Form(
              key: _dropdownFormKey,
              child: Container(
                alignment: Alignment.center,
                padding: const EdgeInsets.symmetric(horizontal: 15),
                width: double.infinity / 2,
                margin: const EdgeInsets.only(
                  left: 20,
                  right: 20,
                  bottom: 20,
                ),
                decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border.all(
                    width: 1,
                    color: Colors.black38,
                  ),
                  borderRadius: BorderRadius.circular(06),
                ),
                child: StatefulBuilder(builder: ((context, setState) {
                  return DropdownButtonFormField<String>(
                    decoration: const InputDecoration(border: InputBorder.none),
                    validator: (value) =>
                        value == null ? "Select a Fruit" : null,
                    // value: dropdown,
                    icon: const Align(
                        alignment: Alignment.centerRight,
                        child: Icon(Icons.keyboard_arrow_down)),
                    items: item.map((e) {
                      return DropdownMenuItem<String>(
                        value: e,
                        child: Text(e),
                      );
                    }).toList(),
                    onChanged: (String? value) {
                      setState(() {
                        dropdown = value!;
                      });
                    },
                  );
                })),
              ),
            ),
            ElevatedButton(
              onPressed: () {
                if (_dropdownFormKey.currentState!.validate()) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text('$dropdown successfully added'),
                    ),
                  );
                }
              },
              child: const Text("Submit"),
            ),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              width: double.infinity / 2,
              margin: const EdgeInsets.only(
                left: 20,
                right: 20,
                bottom: 20,
              ),
              decoration: BoxDecoration(
                  border: Border.all(
                width: 1,
                color: Colors.black26,
              )),
              child: StatefulBuilder(builder: ((context, setState) {
                return DropdownButton<MenuItem>(
                  isExpanded: true,
                  underline: const SizedBox(),
                  value: dropdownValue,
                  icon: const Align(
                      alignment: Alignment.centerRight,
                      child: Icon(Icons.keyboard_arrow_down)),
                  items: menuItems.map((e) {
                    return DropdownMenuItem<MenuItem>(
                      value: e,
                      child: Row(
                        children: [
                          Icon(
                            e.icon,
                            size: 20,
                            color: Colors.black12,
                          ),
                          const SizedBox(
                            width: 15,
                          ),
                          Text(e.text),
                        ],
                      ),
                    );
                  }).toList(),
                  onChanged: (MenuItem? value) {
                    setState(() {
                      dropdownValue = value!;
                    });
                  },
                );
              })),
            ),
          ],
        ),
      ),
    );
  }
}

In the above code, we have used two dropdown buttons. The first dropdown button that we have used is DropDownButtonFormField which is mostly used in the case of creating a form and selecting a different option with validation. Here we have used a Button to add the item and display its message on the snack bar widgets second dropdown button that we have used is DropDownButton which is a normal dropdown button mostly used in the flutter application and has no validation feature too.

Meanwhile, when we run this application in the emulator or device, we should get the UI similar to the screenshot below:

Thanks for reading this article on implementing DropDownMenuButton In Flutter. Also read: Guide On Implementing GridView In Flutter