My problem is:
- I fill a DropDownList with records obtained from an API
- Then I select one of the items and this event fills a second DropDownList, which, like the first one, receives data from an API
- When I click on the first DropDownList again I get the error:
Code of the first DropDownList
Widget _regionesContainer() {
return new Container(
child: new DropdownButton<String>(
items: dataRegion.map((item) {
return new DropdownMenuItem<String>(
value: item['ID_REGION'].toString(),
child: new Text(item['NOMBRE_REGION'],
style: new TextStyle(fontSize: 13.0)
),
);
}).toList(),
hint: Text("Seleccione región"),
onChanged: (String newValReg) {
setState(() {
_mySelectionReg = newValReg;
capturaComuna(newValReg);
Fluttertoast.showToast(msg: _mySelectionReg,
fontSize: 18.0,
);
});
},
value: _mySelectionReg,
),
margin: EdgeInsets.only(bottom: 40.0)
);
}
This is the code for the second DropDownList
Widget _comunasContainer() {
return new Container(
child: new DropdownButton<String>(
items: dataComuna.map((item) {
return new DropdownMenuItem<String>(
value: item['ID_COMUNA'].toString(),
child: new Text(item['NOMBRE_COMUNA'],
style: new TextStyle(fontSize: 13.0)),
);
}).toList(),
hint: Text("Seleccione comuna"),
onChanged: (newValCom) {
_mySelectionCom = newValCom;
setState(() {
});
},
value: _mySelectionCom,
),
margin: EdgeInsets.only(bottom: 45.0)
);
}
This is the code for the future methods:
String _mySelectionReg;
String _mySelectionCom;
String urlRegion = "http://www.aquimaestros.cl/am/Region/Read.php";
List dataRegion = List(); //Lista de regiones
List dataComuna = List(); //Lista de comunas
Future<String> getSWData() async {
var res = await http
.get(Uri.encodeFull(urlRegion), headers: {"Accept": "application/json"});
var resBody = json.decode(res.body);
setState(() {
dataRegion = resBody;
});
print(resBody);
return "Sucess";
}
Future<String> capturaComuna(String _id) async {
String urlComuna = "http://www.aquimaestros.cl/am/Comuna/ReadxRegion.php?id_region=${_id}";
var res = await http
.get(Uri.encodeFull(urlComuna), headers: {"Accept": "application/json"});
var resBody = json.decode(res.body);
setState(() {
dataComuna = resBody;
});
print(resBody);
return "Sucess";
}
The error occurs when clicking a second time on the DropDownList of the _regionesContainer widget, this is the error:
This happens only if you already selected an element in the second
DropdownButton
. By selecting an item you are updating the value of the attribute_mySelectionCom
with the selected value. When you select another item in the first oneDropDownButton
you need to clear the attribute_mySelectionCom
so that the second oneDropdownButton
doesn't try to search_mySelectionCom
within itsitems
Clear the attribute
_mySelectionCom
: