简体   繁体   中英

checkbox in listView.separated in flutter

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,
)

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(() {});
          },
        ),
      ),
    );
  }
}
Row( children: [ Text(list[index].name), SizedBox(width: 10), CheckboxListTile( value: value, onChanged: (bool value) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM