CheckBox

多选按钮:
class CheckboxPage extends StatefulWidget {
  const CheckboxPage({super.key});
  @override
  State<CheckboxPage> createState() => _CheckboxPageState();
}
class _CheckboxPageState extends State<CheckboxPage> {
  bool _flag = true;
  _onChanged(value) {
    setState(() {
      _flag = !_flag;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Checkbox'),
      ),
      body: Center(
        child: Column(
          children: [
            const Text("多选按钮:"),
            Checkbox(value: _flag, onChanged: _onChanged)],
        ),
      ),
    );
  }
}
多选按钮组:
class CheckboxPage extends StatefulWidget {
  const CheckboxPage({super.key});
  @override
  State<CheckboxPage> createState() => _CheckboxPageState();
}

class _CheckboxPageState extends State<CheckboxPage> {
  bool _flag = true;
  final List _hobby = [
    {"checked": true, "title": "吃饭"},
    {"checked": false, "title": "睡觉"},
    {"checked": true, "title": "代码"}
  ];
  List<Widget> _getHobby() {
    List<Widget> tempList = [];
    for (var i = 0; i < _hobby.length; i++) {
      tempList.add(Row(
        children: <Widget>[
          Text(_hobby[i]["title"] + ":"),
          Checkbox(
              value: _hobby[i]["checked"],
              onChanged: (value) {
                setState(() {
                  _hobby[i]["checked"] = value;
                });
              })
        ],
      ));
    }
    return tempList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Checkbox'),
      ),
      body: Center(
        child: ListView(
          padding: const EdgeInsets.all(5),
          children: [
            const SizedBox(height: 40),
            Column(
              children: _getHobby(),
            ),
            const SizedBox(
              height: 20,
            ),
            ElevatedButton(
                onPressed: () {
                  print(_hobby);
                },
                child: Text("获取爱好"))
          ],
        ),
      ),
    );
  }
}

 

 

 

posted on 2024-01-31 18:14  鲤斌  阅读(20)  评论(0)    收藏  举报