Search code examples
flutterdartbuilder

I ran into a problem with Switches in flutter


I'm on the max course, and ran into a problem. I have 4 switches which are created by builder:

//here are variables used later to pass data into builder
  bool _glutenFree = false;
  bool _vegetarian = false;
  bool _vegan = false;
  bool _lactoseFree = false;

Widget _buildSwitchListTile(
String title,
String description,
bool currentValue,
Function(bool) updateValue,


) {
    return SwitchListTile(
      title: Text(title),
      value: _glutenFree,
      subtitle: Text(description),
      onChanged: updateValue,
    );
  }

When I try to click the 2nd, 3rd, 4th switch, nothing happens. But when I try to click the first one, all four switch.

here is how _buildSwitchListTile is used:

_buildSwitchListTile(
                'Gluten-free',
                'Only include gluten-free meals.',
                _glutenFree,
                (newValue) {
                  setState(
                    () {
                      _glutenFree = newValue;
                    },
                  );
                },
              ),
              _buildSwitchListTile(
                'Lactose-free',
                'Only include Lactose-free meals.',
                _lactoseFree,
                (newValue) {
                  setState(
                    () {
                      _lactoseFree = newValue;
                    },
                  );
                },
              ),
              _buildSwitchListTile(
                'Vegetarian',
                'Only include Vegetarian meals.',
                _vegetarian,
                (newValue) {
                  setState(
                    () {
                      _vegetarian = newValue;
                    },
                  );
                },
              ),
              _buildSwitchListTile(
                'Vegan',
                'Only include Vegan meals.',
                _vegan,
                (newValue) {
                  setState(
                    () {
                      _vegan = newValue;
                    },
                  );
                },
              ),

I know that the Max's course is a bit outdated now,I usually analyze the problems myself, but everything seems logical here. Has anyone ever had a similar problem?


Solution

  • change _glutenFree to currentValue

        //here are variables used later to pass data into builder
        bool _glutenFree = false;
        bool _vegetarian = false;
        bool _vegan = false;
        bool _lactoseFree = false;
    
        Widget _buildSwitchListTile(
        String title,
        String description,
        bool currentValue,
        Function(bool) updateValue,
    
    
        ) {
         return SwitchListTile(
          title: Text(title),
          value: currentValue,    // change _glutenFree to currentValue
          subtitle: Text(description),
          onChanged: updateValue,
        );
      }