UI
in my code when two parameters has in country dropdown
when selected India, then show Indian provinces. Also, when selected USA, then show USA provinces in the province dropdown the way, after selecting a province, and again when changing the country, then show an error.
How to resolve this error when like that scenario I want show warning message or when change country then province should be to change initial value.
code
class _HomePageState extends State<HomePage> {
List<String> countries = ['USA', 'India'];
List<String> indiaProvince = ['New Delhi', 'Bihar', 'Rajasthan'];
List<String> usaProvince = ['Texas', 'Florida', 'California'];
List<String> provinces = [];
String? selectedCountry;
String? selectedProvince;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Multi Level Dropdown'),
),
body: ListView(
padding: EdgeInsets.all(20.0),
children: [
// Country Dropdown
DropdownButton<String>(
hint: Text('Country'),
value: selectedCountry,
isExpanded: true,
items: countries.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (country) {
if (country == 'USA') {
provinces = usaProvince;
} else if (country == 'India') {
provinces = indiaProvince;
} else {
provinces = [];
}
setState(() {
selectedProvince != 'null';
selectedCountry = country;
});
},
),
// Country Dropdown Ends here
// Province Dropdown
DropdownButton<String>(
hint: Text('Province'),
value: selectedProvince,
isExpanded: true,
items: provinces.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (province) {
setState(() {
selectedProvince = province;
});
},
),
// Province Dropdown Ends here
],
),
);
}
}
2
Answers
There is duplication of values in your Drop down, you need to exclude duplication using some way, I recommend using
toSet()
,instead of this part of your code:Change it to this:
then try running again
Your issue is that you push
indiaProvince
andusaProvince
intoprovinces
every time country change, when you change country twice you will push two timesindiaProvince
intoprovinces
, so change your country’s onChanged to this: