'Flutter DropDownButton using FutureBuilder value is not updating after selecting values from DropdownItems
I have been trying to code this app using Flutter and I want to make a Dropdown that displays the values received from a JSON response via provider. The response is successful from the service and correctly fetches the data. Dropdown is wrapped in a FutureBuilder, the information can be displayed without problems in the Dropdown, the problem is generated when I want to select an element, it is not updated, for this reason it is not reflected.
My code:
List<Datum> listDatumEnterprise;
Datum _selectEnterprise;
return FutureBuilder(
future: getInformationAdministrative.enterpriseDataGet(),
builder: (BuildContext context, AsyncSnapshot<List<Datum>> snapshot) {
if (snapshot.hasData) {
listDatumEnterprise = snapshot.data;
return CustomDropDown<Datum>(
title: 'Selecciona empresa',
value: _selectEnterprise,
onChanged: (Datum datum) {
setState(() {
_selectEnterprise = datum;
print(_selectEnterprise.id);
});
},
dropdownMenuItemList: listDatumEnterprise?.map((Datum item) {
return new DropdownMenuItem<Datum>(
child: Text(item.alias),
value: item,
);
})?.toList() ??
[],
);
} else {
return CircularProgressIndicator();
}
Solution 1:[1]
The problem is that you are initializing _selectEnterprise
inside your build
, calling setState()
will call build and will re-initiate the value again to empty, move Datum _selectEnterprise
outside your build
. Also be sure to have distinct values for the DropdownMenuItem
.
Solution 2:[2]
I have wrapped my DropdownButton with StatefulBuilder. This is the only way I could change the data of DropdownButton without recalling FutureBuilder.
Demo code:
StatefulBuilder(builder: (context, setState) {
return DropdownButton<String>(
borderRadius: BorderRadius.circular(
10,
),
hint: Text(
"Your Hint",
),
value: selectedValue, //your selected value
isExpanded: true,
items: your_list.map((String value) { //your list here
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (value) {
setState(() => selectedValue = value); //your selected value
},
);
}),
Learn more from: StatefulBuilder
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ikerfah |
Solution 2 | Bihim |