Flutter DropDownButton Tutorials

DropdownButton widget consists a list of DropdownMenuItem. It shows the currently selected item and an arrow that opens a menu for selecting another item.

A simple DropdownButton

A simple widget consists of list of String and its respective value.

String _selectedValue;
DropdownButton<String>(
  value: _selectedValue,
  isExpanded: true,
  items: [
    DropdownMenuItem<String>(
      value: "anime",
      child: Text(
        "Anime",
        style: TextStyle(color: Colors.red),
      ),
    ),
    DropdownMenuItem<String>(
      value: "manga",
      child: Text(
        "Manga",
        style: TextStyle(color: Colors.blue),
      ),
    ),
  ],
  onChanged: (value) {
    setState(() {
      _selectedValue = value;
    });
  },
  hint: Text(
    "Category",
  ),
)

Set DropdownButton values from a list

The list can be a list of primitive Data Types or Object.

final List<String> categories = ['Favorite', 'Happy', 'Sad', 'Angry'];
String _selectedValue;
DropdownButton<String>(
  value: _selectedValue,
  isExpanded: true,
  items: categories.map((e)  {
    return DropdownMenuItem<String>(
      value: e,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Icon(Icons.label),
          Text(e)
        ],
      ),
    );
  }).toList(),
  onChanged: (value) {
    setState(() {
      _selectedValue = value;
    });
  },
  hint: Text(
    "Category",
  ),
)

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close