I am trying to make dependent multilevel dropdown first contains states list and second contains cities list, all the data fetched from API. Initially, I load state dropdown
I am also facing a problem until new state data is not fetched It is showing previous state data. The approach I have used is different. I am not using future Builders. Here is My code:
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Expanded(
child: new Container(
width: 450,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Source",
style: TextStyle(
fontSize: 15, fontWeight: FontWeight.bold),
),
source1 != null ? DropdownButtonFormField<String>(
isExpanded: true,
validator: (value) => value == null ? 'field required' : null,
hint: Text("Select Source"),
items: source1.data.map((item) {
// print("Item : $item");
return DropdownMenuItem<String>(
value: item.descr,
child: Text(item.descr),
);
}).toList(),
onChanged: (String cat) {
setState(() {
subsourseStr = null;
sourceStr = cat;
getSubSource2(sourceStr);
});
},
value: sourceStr,
):SizedBox(height: 10),
],
),
),
)
],
),
),
//
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Expanded(
child: new Container(
width: 450,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Sub Source",
style: TextStyle(
fontSize: 15, fontWeight: FontWeight.bold),
),
subSource2 != null ? DropdownButtonFormField<String>(
isExpanded: true,
validator: (value) => value == null ? 'field required' : null,
hint: Text("Select Sub Source"),
items: subSource2.data.map((item) {
return DropdownMenuItem<String>(
value: item.descr,
child: Text(item.descr),
);
}).toList(),
onChanged: (String cat) {
setState(() {
subsourseStr = cat;
});
},
value: subsourseStr,
):SizedBox(height: 10,),
],
),
),
)
],
),
),
You have to make cityModel = null
in onChanged
callback of State dropdown.
setState(() {
cityModel = null;
stateModel = selectedState;
_city = _fetchCities(stateModel.billstateid);
});
There should be exactly one item with [DropdownButton]'s value: Instance of 'City'. Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
This error occurs here, because the value
you are passing not in the items
of DropdownButtonFormField
(city dropdown).
When you select a State, you are fetching new list of city list and passing it to CityDropDown but forgot to clear the previously selected city(cityModel
).
You can also refer this example: DartPad