SOS video
SOS video

Reputation: 476

Uncheck a checkbox when user checking another one (bool of checkbox is in a map)

I have in my app a few checkboxes and I want, when the user checks a checkbox, that the other checkboxes are unchecked. That's normally not difficult at all, but the problem is that I have the bool and the title of the checkbox in a map. How can I uncheck all checkboxes except the one the user checkt?

This is the map:

Map<String, bool> filterOptions = {
  'Test1': false,
  'Test2': false,
};

This is the code where I "build" the checkboxes:

ListView(
    scrollDirection: Axis.vertical,
    shrinkWrap: true,
    children: filterOptions.keys.map((String key) {
      return CheckboxListTile(
        title: Text(key),
        value: filterOptions[key],
        onChanged: (bool value) {
          setState(() {
            filterOptions[key] = value;
          });
        },
      );
    }).toList(),
  ),

Upvotes: 1

Views: 567

Answers (2)

Steven Ogwal
Steven Ogwal

Reputation: 802

The purpose of a checkbox is for multiple user group selection. In other words, if you want to unselect when a user selects another option then

RadioButton

would be the best option.

SingingCharacter _character = SingingCharacter.lafayette;


Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        ListTile(
          title: const Text('Male'),
          leading: Radio(
            value: SingingCharacter.lafayette,
            groupValue: _character,
            onChanged: (SingingCharacter value) {
              setState(() {
                _character = value;
              });
            },
          ),
        ),
        ListTile(
          title: const Text('Female'),
          leading: Radio(
            value: SingingCharacter.jefferson,
            groupValue: _character,
            onChanged: (SingingCharacter value) {
              setState(() {
                _character = value;
              });
            },
          ),
        ),
      ],
    );
  }

Screenshotenter image description here

Source: Flutter RadioButton

Upvotes: 1

FrontMobe
FrontMobe

Reputation: 346

What you are looking for is not a checkbox, but a Radio Button. You can only select one radio button at a time and you don't have to manually check the state. However, if you insist on the checkboxes you can iterate through the map

filterOptions.forEach((key, value) => filterOptions[key] = false);

If you set value to false, you will just change the copy of the value. You might consider dropping the map and go for a single int selectedBox variable.

Upvotes: 1

Related Questions