Flutter基础组件: Switch CheckBox

2022-05-18  本文已影响0人  Roct

SwitchCheckbox属性比较简单,读者可以查看API文档,它们都有一个activeColor属性,用于设置激活态的颜色。至于大小,到目前为止,Checkbox的大小是固定的,无法自定义,而Switch只能定义宽度,高度也是固定的。

Switch

class _MyHomeApp extends StatefulWidget {
  const _MyHomeApp({Key? key}) : super(key: key);

  @override
  State<_MyHomeApp> createState() => _MyHomeAppState();
}

class _MyHomeAppState extends State<_MyHomeApp> {
  bool _selectedSwitch = true;


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("设置"),
          centerTitle: true,
        ),
        body: Column(children: [
          Switch(
              value: _selectedSwitch,
              onChanged: (val) {
                setState(() {
                  _selectedSwitch = val;
                });
              }),
        ]));
  }
}

CheckBox

class _MyHomeApp extends StatefulWidget {
  const _MyHomeApp({Key? key}) : super(key: key);

  @override
  State<_MyHomeApp> createState() => _MyHomeAppState();
}

class _MyHomeAppState extends State<_MyHomeApp> {

  bool _selectedCheckbox = false;


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("设置"),
          centerTitle: true,
        ),
        body: Column(children: [
          Checkbox(
              value: _selectedCheckbox,
              onChanged: (val) {
                setState(() {
                  _selectedCheckbox = val as bool;
                });
              })
        ]));
  }
}

CheckBox 设置半选

tristate为true的时候, checkbox的值可以为null, null就是半选


class _MyHomeAppState extends State<_MyHomeApp> {

  dynamic _selectedCheckbox = null;
  bool _selectedSwitch = true;


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("设置"),
          centerTitle: true,
        ),
        body: Column(children: [
          Switch(
              value: _selectedSwitch,
              onChanged: (val) {
                setState(() {
                  _selectedSwitch = val;
                });
              }),
          Checkbox(
              tristate: true,
              value: _selectedCheckbox,
              onChanged: (val) {
                setState(() {
                  _selectedCheckbox = val as bool;
                });
              })
        ]));
  }
}
上一篇下一篇

猜你喜欢

热点阅读