skip to Main Content

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


  1. setState causes rebuild.

    You put variable initialization in build method.

    You have to move variable outside build method.

    String selectedCategoryFood = '';
    Widget build(BuildContext context) {...}
    
    Login or Signup to reply.
  2. The problem is that you have defined selectedCategoryFood within your build method:

    Widget build(BuildContext context) {
    var selectedCategoryFood = "";
    

    So, every setState it gets reset.

    To fix the issue, declare selectedCategoryFood in your _state class:

    class _TestState extends State<Test> {
      var selectedCategoryFood = "";
      @override
      Widget build(BuildContext context) {
        return Scaffold(
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search