Create Dynamic Dropdown Buttons in Flutter

Flutter Aug 14, 2023

Dropdown buttons are important user interface components in Flutter for presenting a list of options that users can select from. In this post, we will explore how to implement dropdown buttons using Flutter's built-in DropdownButton widget. We will start with a basic implementation and then go over improvements and customization options.

Basic implementation

For the basic implementation, we will create a dropdown button that will display a list of languages, let us take a look at the code:

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String language = 'english';

  String titleCase(String string) => string[0].toUpperCase() + string.substring(1);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Current language: ${titleCase(language)}'),
        ),
        body: Center(
          child: DropdownButton<String>(
            value: language,
            onChanged: (String? value) =>
                setState(() => language = value ?? language),
            items: [
              DropdownMenuItem(value: 'english', child: Text('English')),
              DropdownMenuItem(value: 'german', child: Text('German ')),
              DropdownMenuItem(value: 'spanish', child: Text('Spanish')),
            ],
          ),
        ),
      ),
    );
  }
}

In this code snippet, we set up a simple application. Inside the MyApp widget, we have got a language variable to keep track of the chosen language. We also got a function called titleCase, that makes the first letter of a given string uppercase. This function is used in the title of the AppBar.

In the build function, we return our MaterialApp. Inside the MaterialApp we have our Scaffold widget to create our page layout. Inside the Scaffold widget we define our DropdownButton.

In the DropdownButton widget, we set three properties: value, onChanged, and items. The value property holds the current chosen option, which we set to the language variable. The onChanged property uses a callback to switch from the current to the newly selected value. In this situation, it updates our selected language. Finally, the items property holds a list of DropdownMenuItem widgets. We have defined three DropdownMenuItems, each representing a language choice.

When we built our application you will see that we can select between three languages and once a new language is selected the title of the AppBar widget changes accordingly.

flutter_selecting_new_language_using_dropdown_button

Dynamic implementation

Now with the basic implementation finished, let us improve our implementation by introducing a more dynamic approach:

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String language = 'english';
  List<String> languages = [
    'english',
    'german',
    'spanish',
  ];

  String titleCase(String string) => string[0].toUpperCase() + string.substring(1);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Current language: ${titleCase(language)}'),
        ),
        body: Center(
          child: DropdownButton<String>(
            value: language,
            onChanged: (String? value) =>
                setState(() => language = value ?? language),
            items: languages
                .map((String language) => DropdownMenuItem(
                      value: language,
                      child: Text(titleCase(language)),
                    ))
                .toList(),
          ),
        ),
      ),
    );
  }
}

In this code snippet, we refactored the previous code:

In the previous code snippet, the available languages are directly defined within the items property of the DropdownButton. In this updated code snippet, the available languages are stored in a separate List<String> named languages. This list is then used to generate the DropdownMenuItem widgets.

Now the DropdownMenuItem widgets are generated using the map function on this languages list. This allows us to dynamically create a DropdownMenuItem widget for each language in the list.

Both code versions do the same thing: make a language choice dropdown and show the selected language in the title bar. But the updated code snippet is more dynamic. It keeps languages in a list and uses a map function to make DropdownMenuItem widgets. This makes the code more maintainable and scalable if additional languages need to be added in the future.

flutter_selecting_new_language_using_dropdown_button_using_refactored_code

Customization

To change the size of the dropdown button and menu we can wrap our DropdownButton widget with a Container widget, see the code below:

body: Center(
  child: Container(
    width: 300,
    child: DropdownButton<String>(
      isExpanded: true,
      ...
    ),
  ),
),

In this code snippet, we wrapped the DropdownButton widget with a Container widget. We defined a width of 300 to make the dropdown menu wider. To make sure that the button has the same width we added the isExpanded property with a value of true to the DropdownButton widget.

flutter_showcasing_dropdown_button_with_increased_width

Hiding the underline

It might be hard to spot, but if you check the previous GIF again, you might notice a small underline underneath the dropdown button. It is possible to hide this line, see the code below:

DropdownButtonHideUnderline(
  child: DropdownButton<String>( ... ),
),

In this code snippet, we wrapped our DropdownButton widget with the DropdownButtonHideUnderline widget to hide the underline:

flutter_hiding_underline_of_dropdown_button

Conclusion

In this post, we explored the process of creating dynamic dropdown buttons using Flutter's DropdownButton widget. We started with a basic implementation, improved it using a more dynamic approach, and then customized its appearance by adjusting the width and hiding the underline. Dropdown buttons are flexible elements that can be adapted to different designs, letting users easily choose options in Flutter applications.

Tags