美文网首页
Flutter基础组件: Switch CheckBox

Flutter基础组件: Switch CheckBox

作者: Roct | 来源:发表于2022-05-18 14:45 被阅读0次

    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;
                    });
                  })
            ]));
      }
    }
    

    相关文章

      网友评论

          本文标题:Flutter基础组件: Switch CheckBox

          本文链接:https://www.haomeiwen.com/subject/wkfwurtx.html