Home > database >  Flutter - add together the number of SwitchListTile = true
Flutter - add together the number of SwitchListTile = true

Time:03-10

I have an app I'm working on. It sounds simple in theory of what I want to do, but just cannot make it work.

I want to output Text of how many of the SwitchLiStTile's are true. There are 8 SwitchListTiles, if someone clicks the 3rd and 5th ones, I want the output to be 2. I cannot grasp how I would acomplish this. Everything I have tried has failed. If I could just make the value of the Switch an integer, this would be simple.

bool cng1 = false;
bool cng2 = false;

SwitchListTile(
title: const Text('Switch One'),
value: _user.wat1,
onChanged: (bool val) =>
setState(() => cng1 = val)),
SwitchListTile(
title: const Text('Switch Two'),
value: _user.wat2,
onChanged: (bool val) =>
setState(() => cng2 = val)),

Granted, if there was truly on 2 switches, this would be way easier. There are 8 and will be more. This is just shorthand code because I felt I needed to put something. How would I go about getting this solved? I have tried converting the Bools to integers and that just adds more problems. I Can't just use a Dart Operator to add them together when they are not integers anyways. Nothing seems to work without writing line after line, within a HUGE if statement. I'm working with 8 switches which give a huge number of possibilities. Any help would be awesome.

CodePudding user response:

use a List:

final listCng = [true/false] // 8 value default;

Code:

final listCng = [false, false, false, false, false, false, false, false];

return ListView.builder(
    itemBuilder: (context, index) => SwitchListTile(
        title: const Text('Switch One'),
        value: _user.wat1,
        onChanged: (bool val) => setState(() {
              // option value 3 || value 5
              if (index == 2 || index == 4) {
                listCng[index] = val;
                return;
              }

              // option other
              listCng[index] = val;
            })));

CodePudding user response:

You can wrap the data in GestureDetector and have a count variable which is updated onTap.

bool cng1 = false;
bool cng2 = false;
int count = 0;

GestureDetector(
  onTap: () => count  ,
  SwitchListTile(
    title: const Text('Switch One'),
    value: _user.wat1,
    onChanged: (bool val) =>
    setState(() => cng1 = val)),
)

If the number is supposed to be displayed in the UI in reactive manner, you can wrap the count in a setState.

  • Related