I’m trying to get a list from my firebase firestore and provide it as a dropdown button, but when the user selects the option it does not update on GUI.
I think the problems is where I instantiate the dropdownValue variable but I don’t where else to place it.
class _LocationNameListState extends State<LocationNameList> {
@override
Widget build(BuildContext context) {
List dropdownOptions = <String>[];
String? dropdownValue;
return StreamBuilder(
stream: LocationController().getAllLocations(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text("This is something wrong");
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
}
for (var i = 0; i < snapshot.data!.docs.length; i++) {
dropdownOptions.add("${snapshot.data!.docs[i]['name']}");
}
print(dropdownOptions);
String dropdownValue = dropdownOptions[0];
return DropdownButton(
items: dropdownOptions
.map((e) => DropdownMenuItem(
value: e,
child: Text(e),
))
.toList(),
onChanged: (value) {
setState(() {
dropdownValue = value.toString();
print(dropdownValue);
});
},
value: dropdownValue,
);
},
);
}
}
2
Answers
The problem is that your
dropDown
value is set within yourBuild
method:So every
setState
it gets reset, since thebuild
rebuilds.To fix the error, move your
value
outside of the build method:I’ve managed to reproduce your problem with a simplified example. As you see
dropdownValue
will be reset, since it’s within the build method:And to solve the issue:
Every time setState is called, build method gets called. It means
String dropdownValue = dropdownOptions[0];
is called as well setting the value of variable to first item of the list.You need to move
dropdownValue
to class level variable of your state class.(
String? dropdownValue = null
)Then replace above mentioned line with