一.单选开关Switch和CheckBox属性介绍
1.flutter中提供了Material风格的单选开关Switch和复选框Checkbox,它们都是继承自StatefulWidget,但它们本身不会保存当前选中状态,选中状态都是由父组件来管理的,当Switch或Checkbox发生改变时,会触发它们的onChanged回调.
2.switch源码查看,eg:
const Switch({
Key? key,
required this.value, //@required bool,value = true 时为打开状态,false 关闭
required this.onChanged, //点击事件
this.activeColor, //激活状态下滑块颜色
this.activeTrackColor, //激活状态下轨道颜色
this.inactiveThumbColor, //关闭状态下滑块颜色
this.inactiveTrackColor, //关闭状态下轨道颜色
this.activeThumbImage, //激活状态下滑块图片
this.onActiveThumbImageError, //激活状态下滑块图片加载失败回调
this.inactiveThumbImage, //关闭状态下滑块图片
this.onInactiveThumbImageError, //关闭状态下滑块图片加载失败回调
this.thumbColor, //内边距
this.trackColor,
this.materialTapTargetSize,
this.dragStartBehavior = DragStartBehavior.start,
this.mouseCursor, //鼠标光标
this.focusColor, //聚焦颜色
this.hoverColor, //悬停颜色
this.overlayColor,
this.splashRadius,
this.focusNode, //焦点控制
this.autofocus = false, //自动聚焦
})
3.Checkbox源码查看,eg:
const Checkbox({
Key? key,
required this.value, //@required bool,value = true 时为选中状态,false 关闭
this.tristate = false, //默认false,如果为true,复选框的值可以为true、false或null(表示是否为三态)
required this.onChanged, //点击事件
this.mouseCursor, //鼠标光标
this.activeColor, 激活状态下使用的颜色
this.fillColor,
this.checkColor, //选中此复选框时用于复选图标的颜色
this.focusColor, //聚焦颜色
this.hoverColor, //悬停颜色
this.overlayColor,
this.splashRadius,
this.materialTapTargetSize,
this.visualDensity,
this.focusNode, //焦点控制
this.autofocus = false, //自动聚焦,默认为 false
this.shape,
this.side,
}
二. SwitchAndCheckBoxTestRoute demo展示,eg:
import 'package:flutter/material.dart';
class SwitchAndCheckBoxTestRoute extends StatefulWidget{
@override
_SwitchAndCheckBoxTestRouteState createState() => _SwitchAndCheckBoxTestRouteState();
}
class _SwitchAndCheckBoxTestRouteState extends State<SwitchAndCheckBoxTestRoute>{
bool _switchSelected=true;//单选开关状态
bool _checkboxSelected=true;//复选框开关
@override
Widget build(BuildContext context) {
return Column(
children: [
Switch(
value: _switchSelected, //当前状态
onChanged: (value){
setState(() {//重新构建页面
_switchSelected=value;
print('switch value is $_switchSelected');
});
}
),
Checkbox(
value: _checkboxSelected,
activeColor: Colors.red,//选中时颜色
onChanged: (value){
setState(() {
_checkboxSelected=value!;
print('checkbox value is $_checkboxSelected');
});
}
),
TextField(
autofocus: true,
decoration: InputDecoration(
labelText: "user name",
hintText: "email",
prefixIcon: Icon(Icons.person)
),
),
TextField(
decoration: InputDecoration(
labelText: "passwd",
hintText: "your passwd",
prefixIcon: Icon(Icons.lock)
),
obscureText: true,
)
],
);
}
}
上面代码中,SwitchAndCheckBoxTestRoute继承自StatefulWidget ,在其build方法中分别构建了一个Switch和Checkbox,初始状态都为选中状态,当用户点击时,会将状态置反,然后回调用setState()通知 Flutter 框架重新更新UI。