I’ve made a simple class to store my dropdown options:
class ExperienceYearsRepository {
List<String> returnExperienceYears() {
return [
"Menos de 1 ano",
"Entre 1 e 3 anos",
"Entre 3 e 5 anos",
"Mais de 5 anos"
];
}
}
Below, there’s a dropdown implementation which uses that list, but when any option is clicked, the value displayed inside the dropdown is always the value set as experienceYears.first:
String experienceTime = "";
var experienceYearsRepository = ExperienceYearsRepository();
var experienceYears = [];
void initState() {
experienceYears = experienceYearsRepository.returnExperienceYears();
super.initState();
}
DropdownButton(
isExpanded: true,
value: experienceYears.first,
items: experienceYears
.map((experienceYear) => DropdownMenuItem(
value: experienceYear,
child: Text(experienceYear.toString()),
))
.toList(),
onChanged: (selectedExperienceTime) {
setState(() {
debugPrint(selectedExperienceTime as String?);
experienceTime = selectedExperienceTime.toString();
});
}),
Just to clarify, the debugPrint actually prints the correct dropdown item, so the problem in really about displaying it. Any ideas on how to solve this? I’m pretty new to Flutter and I’m having quite a headache, thanks in advance!
3
Answers
The value property of DropdownButton() isn’t just for initialization, it the value currently displayed on the menu. Change your onChanged parameter to update it. You can assign it in the init() method.
It seems like the issue might be related to the fact that the initial value you’re setting for the dropdown is based on
experienceYears.first
, and this value might not be synchronized with theexperienceTime
variable, which is actually storing the selected option.To make sure the selected value is displayed correctly in the dropdown, you should set the initial value of the dropdown to match the value stored in the
experienceTime
variable. Here’s the updated code:By setting the initial value of
experienceTime
in theinitState
method and then using that value for thevalue
property of theDropdownButton
, you ensure that the displayed value matches the selected option. TheonChanged
callback will continue to update theexperienceTime
variable correctly when a new option is selected.Hope this will work.