Dropdown lists or menus are a common UI element used in mobile applications to provide users with a selection of options. In this article, we will walk through the process of adding a DropdownButton in Flutter, a popular framework for building cross-platform mobile apps. In this article, I’ll cover how to create and customize a dropdown in Flutter.
import 'package:flutter/material.dart';
String selectedOption;
List dropdownOptions = ['Option 1', 'Option 2', 'Option 3'];
DropdownButton(
value: selectedOption.isEmpty ? null : selectedOption,
isDense: true,
onChanged: (String? newValue) {
setState(() {
selectedOption = newValue ?? '';
});
},
items: dropdownOptions.map((String value) {
return DropdownMenuItem(
value: value,
child: Text(value),
);
}).toList(),
),
FormField(
builder: (FormFieldState statee) {
return InputDecorator(
decoration: InputDecoration(
errorStyle:
const TextStyle(color: Colors.redAccent, fontSize: 16.0),
hintText: 'Select an option',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0))),
isEmpty: selectedOption == '',
child: DropdownButtonHideUnderline(
child: DropdownButton(
value: selectedOption.isNotEmpty ? selectedOption : null,
isDense: true,
onChanged: (String? newValue) {
setState(() {
selectedOption = newValue ?? '';
});
},
items: dropdownOptions.map((value) {
return DropdownMenuItem(
value: value,
child: Text(value),
);
}).toList(),
),
),
);
},
),
Dropdown
widget can be used in your Flutter app to show and select a single value from a large set of options.If you want just a simple dropdown which doesn’t need any customization like adding validation and other stuff you can go with DropdownButton.If you are required to apply more style and if the dropdown comes under the Form
widget, it is better to use FormField because it has more customization along with inbuilt validation support.