1 | initial version |
To display the complete name and code of a selected country in Flutter's dropdown menu, follow these steps:
Step 1: Create a list of countries and their codes
List<Map<String, dynamic>> countries = [
{"name": "Afghanistan", "code": "AF"},
{"name": "Albania", "code": "AL"},
{"name": "Algeria", "code": "DZ"},
// and so on...
];
Step 2: Create a stateful widget that will hold the selected country and its code
class CountryDropdown extends StatefulWidget {
@override
_CountryDropdownState createState() => _CountryDropdownState();
}
class _CountryDropdownState extends State<CountryDropdown> {
String selectedCountry = '';
String selectedCountryCode = '';
@override
Widget build(BuildContext context) {
return DropdownButton(
hint: Text('Select a country'),
value: selectedCountry,
onChanged: (value) {
setState(() {
selectedCountry = value;
for (var country in countries) {
if (country['name'] == selectedCountry) {
selectedCountryCode = country['code'];
}
}
});
},
items: countries.map((country) {
return DropdownMenuItem(
value: country['name'],
child: Text(country['name']),
);
}).toList(),
);
}
}
Step 3: Display the selected country and code
Text('$selectedCountry ($selectedCountryCode)'),
To add a search bar to the dropdown menu, we can use the autocomplete_textfield
package. Here are the steps:
Step 1: Add the package to your dependencies in pubspec.yaml
dependencies:
autocomplete_textfield: ^1.8.3
Step 2: Use the AutoCompleteTextField
widget instead of the DropdownButton
class CountryDropdown extends StatefulWidget {
@override
_CountryDropdownState createState() => _CountryDropdownState();
}
class _CountryDropdownState extends State<CountryDropdown> {
TextEditingController searchTextController = TextEditingController();
String selectedCountry = '';
String selectedCountryCode = '';
@override
Widget build(BuildContext context) {
return AutoCompleteTextField(
controller: searchTextController,
decoration: InputDecoration(
hintText: 'Search for a country',
border: OutlineInputBorder(),
),
itemSubmitted: (value) {
setState(() {
selectedCountry = value;
for (var country in countries) {
if (country['name'] == selectedCountry) {
selectedCountryCode = country['code'];
}
}
});
},
itemBuilder: (context, suggestion) => ListTile(
title: Text(suggestion),
),
suggestions: countries
.map((country) => country['name'].toString())
.toList(),
);
}
}
Note: The search function in the AutoCompleteTextField
is case sensitive. If you want it to be case insensitive, you'll need to modify the lib/autocomplete_textfield.dart
file in your project's folder by replacing the _filterList
method with the following:
List<String> _filterList(String filter, List<String> filterList) {
if (filter == null || filter.isEmpty) {
return filterList;
}
return filterList.where((item) => item.toLowerCase().contains(filter.toLowerCase())).toList();
}