FlutterGallery

Select

Flutter offers two types of Select Widgets.
The Select Widget is suitable for receiving information from a user's choice of options.

Here we will show you how to use the Select Widget provided by Flutter.

Basic Usage

  • DropdownButton
  • DropdownMenu

There are the above types of Select Widgets provided by Flutter.
DropdownMenu allows text input and features the ability to search for options.

DropdownButton(
value: selectedValue,
items: const [
DropdownMenuItem(value: "Apple", child: Text("Apple")),
DropdownMenuItem(value: "Grape", child: Text("Grape")),
DropdownMenuItem(value: "Lemon", child: Text("Lemon")),
],
),
DropdownMenu(
initialSelection: "Red",
dropdownMenuEntries: [
DropdownMenuEntry(value: "Red", label: "Red"),
DropdownMenuEntry(value: "Green", label: "Green"),
DropdownMenuEntry(value: "Blue", label: "Blue"),
]
)

DropdownButton is useful when you want to create a general selection field.

It can be deactivated by setting onChange to null.
If complex style changes are needed, enclose the field in a widget such as Container() to achieve a wider range of styles.

Container(
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: Colors.black),
borderRadius: BorderRadius.circular(10),
),
child: DropdownButton(
underline: const SizedBox(),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 3),
borderRadius: BorderRadius.circular(10),
items: [...]
),
),

DropdownMenu allows retrieval of choices and is suited for cases with a large number of choices.
Retrieving the selected data can be handled using TextEditingController().

It is a very easy-to-use widget, but since Disable and validation settings cannot be set by default, it is a widget that must be devised for use in forms.

DropdownMenu(
label: const Text("Outline"),
...
inputDecorationTheme: InputDecorationTheme(
labelStyle: const TextStyle(color: Colors.blue),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.lightBlue[100]!)),
focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue)),
),
dropdownMenuEntries: const [
DropdownMenuEntry(value: "Apple", label: "Apple"),
DropdownMenuEntry(value: "Grape", label: "Grape"),
DropdownMenuEntry(value: "Lemon", label: "Lemon"),
]
),

Validation

  • DropdownButtonFormField

Validation of selected data can be handled using DropdownButtonFormField.
The basic usage is not much different from DropdownButton, but by enclosing it in Form()and specifying a validator, you can freely set error messages.

final _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: DropdownButtonFormField(
value: selectedValue,
validator: (value) {
if (value == "Apple") return "Apple is error!";
return null;
},
...
),
),

API

For further information, please refer to the official documentation below.

Previous
Next