Home > database >  How can I only check one checkbox at time?
How can I only check one checkbox at time?

Time:01-03

How can I select/check only one checkbox to be checked at time?

enter image description here

And below is my code

Container(
    child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
            Checkbox(
                checkColor: Colors.white,
                value: isChecked,
                onChanged: (bool value) {
                    setState(() {
                        isChecked = value;
                        // ignore: unnecessary_statements
                        passData(certId);
                    });
                },
            ),
        ],
    )),

CodePudding user response:

Option1 - Using a map to maintain the state

Create a map:

final Map<int, bool> _state = {};

then, check if the value for that index is true/false:

return ListView.builder(itemBuilder: (context, index) {
      return CheckboxListTile(
        value: _state[index] ?? false,
        onChanged: (value) {
          setState(() {
            _state[index] = value!;
          });
        },
        title: Text(_data[index].text),
      );
    });

Option 2 - using a model:

class CheckBoxModel {
  bool isChecked = false;
  String text = "";
  CheckBoxModel({required this.isChecked, required this.text});
}

and then, generate a List of 30 widgets:

final _data = List.generate(
    30, (index) => CheckBoxModel(isChecked: false, text: "Item $index"));

Now, use a ListView.builder and based on the index, to update the corresponding value:


class Testing extends StatefulWidget {
  const Testing({Key? key}) : super(key: key);

  @override
  State<Testing> createState() => _TestingState();
}

class _TestingState extends State<Testing> {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(itemBuilder: (context, index) {
      return CheckboxListTile(
        value: _data[index].isChecked,
        onChanged: (value) {
          setState(() {
            _data[index].isChecked = value!;
          });
        },
        title: Text(_data[index].text),
      );
    });
  }
}

See also

Expansion tile trailing icon updates all in list on interaction with one tile. How can I only change the icon for the expanded tile?

  • Related