如何使复选框选择,取消选择和出售列表中的所有内容?

时间:2020-03-31 10:14:41

标签: flutter dart checkbox

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

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. 这是用于选择和取消选择单个复选框的代码
  2. 可以选择此逻辑中的所有复选框

列表项

 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 {

    }
  });
}

1 个答案:

答案 0 :(得分:1)

要检查所有项目 _selecteCategorysID.addAll(userList);

取消选中所有项目 _selecteCategorysID.clear();