flutter 如何在列表中实现复选框选中、取消选中和全选?

1dkrff03  于 2023-01-18  发布在  Flutter
关注(0)|答案(2)|浏览(452)

如何选择所有复选框?如果我取消选中列表中的任何复选框,那么如何保持所有选中的复选框,而不是取消选中复选框?

class SelectAllCheckbox extends StatefulWidget {
  @override
  _SelectAllCheckboxState createState() => _SelectAllCheckboxState();
}

class _SelectAllCheckboxState extends State<SelectAllCheckbox> {
  List _selecteCategorysID = List();
  bool rememberMe = false;
  List<String>userList=['Sam','John','Rohan','Peter'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body:  Column(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(left: 20, right: 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text("Select All"),
                Checkbox(
                    value: rememberMe,
                    onChanged: _onRememberMeChanged
                )
              ],
            ),
          ),
          SizedBox(
            height: 450,
            child: ListView.builder(
                itemCount: userList.length,
                itemBuilder: (context, item) {
                  return Card(
                      child: CheckboxListTile(
                        selected: false,
                        value: _selecteCategorysID.contains(userList[item]),
                        onChanged: (bool selected) {
                          _onCategorySelected(selected, userList[item]);
                        },

                        title: Text(userList[item]),
                      ));
                }),
          ),
        ],
      ));
  }

逻辑码
1.这是用于选择和取消选择单个复选框的代码
1.可以选中此逻辑中的所有复选框
列表项

void _onCategorySelected(bool selected, category_id) {
    if (selected == true) {
      setState(() {
        _selecteCategorysID.add(category_id);

      });
    } else {
      setState(() {
        _selecteCategorysID.remove(category_id);

      });
    }
  }

逻辑码
这适用于"全选"复选框

void _onRememberMeChanged(bool newValue) => setState(() {
    rememberMe = newValue;

    if (rememberMe) {

      // TODO: Here goes your functionality to select all checkbox
    } else {

    }
  });
}
yyhrrdl8

yyhrrdl81#

检查所有项目

_selecteCategorysID.addAll(userList);

取消选中所有项目

_selecteCategorysID.clear();
elcex8rz

elcex8rz2#

使用map代替list

Map<String,bool> selectedCategoryId = {};

首次初始化selectedCategoryId

for(var i = 0;i < categoryLenght;i++){
  if(selectedCategoryId[categoryId] == null){
   selectedCategoryId[categoryId] = false;
  }
}

示例如果选择一个,

selectedCategoryId[categoryId] = true;

如果选择全部,

selectedCategoryId.forEach((key,value) => selectedCategoryId[key] = true);

如果取消选择全部,

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

如果取消选择一个,

selectedCategoryId[categoryId] = false;

相关问题