Flutter Dropdown Widget

CodeWithFlutter
3 Min Read

The DropdownButton widget in Flutter is used to create a dropdown menu that allows the user to select one value from a list of items. Some of the common properties of the DropdownButton widget are:

  1. items: This property takes a list of DropdownMenuItem objects, which represent the items that will be displayed in the dropdown menu. Each DropdownMenuItem has a value and a child property, where the value is the data that will be returned when the item is selected, and the child is the widget that will be displayed for the item.
  2. value: This property sets the initial value of the dropdown menu. The value should match the value of one of the DropdownMenuItem objects in the items list.
  3. onChanged: This property takes a callback function that will be called whenever the user selects a new item from the dropdown menu. The callback function takes the new value as its argument.
  4. hint: This property takes a widget that will be displayed as a hint in the dropdown button when no value has been selected.

Here’s an example of how to use the DropdownButton widget with some of its properties:

DropdownButton<String>(
  value: selectedValue,
  items: ['Red', 'Green', 'Blue'].map((value) {
    return DropdownMenuItem<String>(
      value: value,
      child: Text(value),
    );
  }).toList(),
  onChanged: (value) {
    setState(() {
      selectedValue = value;
    });
  },
  hint: Text('Select a color'),
)

In this example, the DropdownButton widget is used to allow the user to select one of the colors “Red”, “Green”, or “Blue”. The value property is used to set the initial selected value, and the onChanged property is used to specify a callback function that will be called when the user selects a new value. The hint property is used to display a hint in the dropdown button when no value has been selected.

Share this Article
Leave a comment