A dropdown button is a widget that helps users to select a value or an option from a set of values. The dropdown list is an important element in an app that increases the ease of the users using the app. In this article, we are going to learn how to implement a dropdown list in Flutter.
For example, you have a form with city selection. There are two widgets that you can use to show those city details. One option is using the radio button, which allows for selecting a single value. The other option is to use DropDownButton. In scenarios like this, using a dropdown widget will be the best option. This is because you can add a large list of cities. And when the user selects a city, it will show only that selected city in particular. So, it is much more likely to provide a better user experience to the end-user.
Code to Add DropDown Button in Flutter
class DropDowView extends StatefulWidget { const DropDowView({Key? key}) : super(key: key); @override _DropDowViewState createState() => _DropDowViewState(); } class _DropDowViewState extends State<DropDowView> { String? selectedCity; List<String> citiesList = <String>[ "City A", "City B", "City C", "City D", "City E", "City F", "City G", "City H", ]; @override Widget build(BuildContext context) { return DropdownButton<String>( hint: const Text( 'In which city do you live?', ), isExpanded: true, value: selectedCity, items: citiesList.map((String value) { return DropdownMenuItem<String>( value: value, child: Text( value, ), ); }).toList(), onChanged: (_) { FocusScope.of(context).requestFocus(FocusNode()); FocusScope.of(context).requestFocus(FocusNode()); setState(() { selectedCity = _!; }); }, ); } }
Screenshots of Results
Properties of DropDown Button Widget
- It is a material design for selecting from a list of items or values.
- The DropDown button shows the currently selected item as well as an arrow that opens a list for selecting any item or value.
- It is an easy way to let users select one particular value from multiple values.
- Each DropDownMenuItem in ‘items’ must be specialized with that same type of argument.
Conclusion
I hope this article helps you in creating a drop-down list in Flutter. No doubt, it is not that difficult to implement a dropdown list in Flutter. Surprisingly, you can use the code given above. As I have taken the example of cities data to view the items, you can change the parameters according to your needs. Moreover, if you still have a query or suggestion, you can drop a comment below. FlutterDesk always inspires Flutter App Development enthusiasts to learn to develop apps with Flutter. Also, you can hire Flutter developer if you need any kind of consultancy from ideation to the launch of your app.