Home > front end >  checkbox in listView.separated in flutter
checkbox in listView.separated in flutter

Time:11-13

I am trying to do checkboxes in the list view flutter but when I select one all are selected, I want to select only the one I click not all. also, How I can know which items are selected

here is my code:

 bool value = false;
ListView.separated(
  physics: NeverScrollableScrollPhysics(),
  shrinkWrap: true,
  itemBuilder: (context, index) => Container(
    height: 100,
    width: double.infinity,
    decoration: BoxDecoration(
      border: Border.all(
          color: Colors.grey, width: 1),
    ),
    child: ListTile(
        title: Column(
          mainAxisAlignment:
              MainAxisAlignment.start,
          crossAxisAlignment:
              CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Text(list[index].name),
                SizedBox(width: 10),
                  CheckboxListTile(
                        value: value,
                        onChanged:
                            (bool value) {
                          this.value = value;
                        },
                      )
              ],
            ),
          ],
        ),
    ),
  ),
  separatorBuilder: (context, index) =>
      SizedBox(
    height: 5,
  ),
  itemCount: 5,
)

CodePudding user response:

You are using single bool to select the list. That's why you are getting this behavior. You can create an empty list to tract the selected items.

You can follow this example code

class ChWL extends StatefulWidget {
  const ChWL({super.key});

  @override
  State<ChWL> createState() => _ChWLState();
}

class _ChWLState extends State<ChWL> {
  List<int> list = List.generate(33, (index) => index);
  List<int> selectedItem = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: list.length,
        itemBuilder: (context, index) => CheckboxListTile(
          title: Text("${list[index]}"),
          value: selectedItem.contains(list[index]),
          onChanged: (value) {
            bool isChecked = selectedItem.contains(list[index]);

            if (isChecked) {
              selectedItem.remove(list[index]);
            } else {
              selectedItem.add(list[index]);
            }

            setState(() {});
          },
        ),
      ),
    );
  }
}

CodePudding user response:

 Row(
              children: [
                Text(list[index].name),
                SizedBox(width: 10),
                  CheckboxListTile(
                        value: value,
                        onChanged:
                            (bool value) {
  • Related