I need advice. I have made condition on dropdownMenu, at first it works, but since I made a change in my code, it didn’t work again.
The problem is the user cannot choose the menu.
And here is my code that I made so far:
There is a variable below BuildContext, far in the top:
Widget build(BuildContext context) {
String selectedCategoryFood = '';
Then this is the dropdownMenu:
child: DropdownButton<String>(
icon: Padding(
padding: const EdgeInsets.only(right: 10, top: 8),
child: SvgPicture.asset(
Assets.icons.dropdownIcon.path,
fit: BoxFit.scaleDown,
),
),
style: body1(color: ColorName.blackPrimary),
items: <String>[
'Burger',
'Ice Cream',
].map((String value) {
return DropdownMenuItem(
value: value,
child: Text(value),
);
}).toList(),
hint: Padding(
padding: const EdgeInsets.only(top: 8, left: 10),
child: Text(
style: body1(color: ColorName.grey),
selectedCategoryFood.isEmpty
? 'Category Food'
: selectedCategoryFood),
),
borderRadius: BorderRadius.circular(10),
underline: const SizedBox(),
isExpanded: true,
onChanged: (value) {
if (value != null) {
setState(() {
selectedCategoryFood = value;
});
}
},
),
2
Answers
setState
causes rebuild.You put variable initialization in build method.
You have to move variable outside build method.
The problem is that you have defined
selectedCategoryFood
within yourbuild
method:So, every
setState
it gets reset.To fix the issue, declare
selectedCategoryFood
in your_state
class: