Flutter: DropdownButton Usage and Features
personAhmet Balaman
calendar_today
FlutterDropdownButtonSpinnerWidgetUIForm
DropdownButton is a selection widget known as Spinner in Android, which displays a list when clicked. It's ideal for presenting multiple options to the user and allowing them to make a single selection.
Live Demo
You can try this widget in the interactive example below:
💡 If the example above doesn't load, click DartPad to run it in a new tab.
Basic Usage
DropdownButton is used to select from a list:
String? selectedValue;
DropdownButton<String>(
value: selectedValue,
hint: Text('Make a selection'),
items: ['Option 1', 'Option 2', 'Option 3'].map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (String? newValue) {
setState(() {
selectedValue = newValue;
});
},
)Important Properties
| Property | Description |
|---|---|
value |
The selected value |
hint |
Widget shown when no selection is made |
items |
List of DropdownMenuItem |
onChanged |
Function called when selection changes |
isExpanded |
Adjusts width according to parent |
underline |
Underline widget |
icon |
Dropdown arrow icon |
dropdownColor |
Background color of the dropdown list |
DropdownButtonFormField
DropdownButtonFormField should be preferred for use within forms. It provides validation support.
DropdownButtonFormField<String>(
value: selectedValue,
decoration: InputDecoration(
labelText: 'Category',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.category),
),
items: categories.map((String category) {
return DropdownMenuItem<String>(
value: category,
child: Text(category),
);
}).toList(),
onChanged: (String? newValue) {
setState(() {
selectedValue = newValue;
});
},
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please select a category';
}
return null;
},
)Customized DropdownMenuItem
You can customize each item:
DropdownMenuItem<String>(
value: 'premium',
child: Container(
padding: EdgeInsets.symmetric(vertical: 8),
child: Row(
children: [
Icon(Icons.star, color: Colors.amber),
SizedBox(width: 10),
Text('Premium Membership'),
Spacer(),
Container(
padding: EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(10),
),
child: Text('Recommended', style: TextStyle(color: Colors.white, fontSize: 10)),
),
],
),
),
)Summary
- DropdownButton: Flutter equivalent of Android Spinner
- DropdownMenuItem: Represents list items
- DropdownButtonFormField: Used for form validation
- isExpanded: Controls width
- onChanged: Captures selection changes
DropdownButton is one of the most commonly used widgets for getting single selection from users.