I am new to Flutter so forgive me if the question sounds silly. I am developing a Flutter application that has a DropdownButtonFormField.
String _selectedCity;
String _selectedCountry;
DropdownButtonFormField(
value: _selectedCity,
hint: Container(
child: Text(
"Select City",
),
),
onChanged: (val) {
setState(() {
_selectedCity = val;
_selectedCountry = val;
//what i would like is : _selectedCountry = name
});
print(_selectedCity);
},
items: city.map((city) {
return DropdownMenuItem(
value: city.cityId,
child: Text(city.country),
);
}).toList(),
);
As it is, I can get the city ID from the dropdown. The issue is, I would like to get the city ID and the city Country and store the country in _selectedCountry.
I have tried adding a second parameter to the onchanged but i get an error.
onChanged: (val, country)
I don't know what to try and the Flutter documentation doesnt give much information on how to do this.
I will really appreciate any approach suggestions I can get.
Thank you.
the onChanged
method cannot give your more than one value, but that value doesn't have to be a String!
Lets say you have a class called Region like this:
class Region {
final String country;
final String city;
Region(this.country, this.city);
}
then instead of using String which is default in DropdownButtonFormField you can define it with the Region class. Now the onChange method returns a Region as well and you have access to the all the data in it. so your code would look like this:
Region _selectedRegion;
@override
Widget build(BuildContext context) {
return Scaffold(
body: DropdownButtonFormField<Region>(
value: _selectedRegion,
onChanged: (val) {
setState(() {
_selectedRegion = val;
});
},
items: {your data}.map((regionData) {
return DropdownMenuItem<Region>(
value: Region(regionData.country, regionData.city),
child: Text(regionData.city),
);
}).toList(),
));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.