DropDown Menu
Simple dropdown menu where you can select an item
import 'package:flutter/material.dart';
class ShowDropDownMenu extends StatefulWidget {
const ShowDropDownMenu({Key? key}) : super(key: key);
@override
_ShowDropDownMenuState createState() => _ShowDropDownMenuState();
}
class _ShowDropDownMenuState extends State<ShowDropDownMenu> {
final menuItems = ['Apple', 'Pear', 'Grape', 'Orange'];
String? _dropdownValue;
@override
void initState() {
// Initialize the menu with the first item
// The selection key (value) is the index as a String
_dropdownValue = "0";
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Dropdown Menu")),
body: Container(
padding: const EdgeInsets.all(20),
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("Please select an item"),
const SizedBox(height: 50),
dropDownMenu(context)
],
)
),
);
}
/// **********************************************************************
/// Displays the DropDown menu
/// **********************************************************************
Widget dropDownMenu(BuildContext context) {
return DropdownButton<String>(
elevation: 16,
items: createListOfItems(),
value: _dropdownValue,
onChanged: (String? newValue) {
setState(() {
// newValue is the value of the selected item
_dropdownValue = newValue ?? "";
print("Selected item = $_dropdownValue");
});
},
);
}
/// **********************************************************************
/// Build the list of items from the menuItems list
/// **********************************************************************
List<DropdownMenuItem<String>> createListOfItems() {
final items = List<DropdownMenuItem<String>>.generate(
menuItems.length,
(index) => DropdownMenuItem(
value: "$index",
child: Text(menuItems[index])));
return items;
}
}