简体   繁体   English

listView 中的复选框。在 flutter 中分隔

[英]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.我正在尝试在列表视图 flutter 中做复选框,但是当我 select 全部被选中时,我只想 select 我点击的不是全部。 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.您正在使用单个 bool 到 select 列表。 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) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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