Material 组件库中提供了单选框 Switch 与复选框 Checkbox ,并且虽然他们都是集成自StatefulWidget ,但是他们不会保存自己的状态,仔细想一下原因是这个状态肯定是外部需要的,由外部来控制他们的状态是比较合理的
先来看一下构造方法
const Switch({
Key key,
@required this.value,///是否勾选value
@required this.onChanged,///bool类型回调
this.activeColor,///勾选后头颜色
this.activeTrackColor,///勾选后进度条颜色
this.inactiveThumbColor,///不勾选头颜色
this.inactiveTrackColor,///不勾选进度条颜色
this.activeThumbImage,///勾选后头部图片
this.onActiveThumbImageError,
this.inactiveThumbImage,///不勾选头部图片
this.onInactiveThumbImageError,
this.materialTapTargetSize,
this.dragStartBehavior = DragStartBehavior.start,
this.mouseCursor,
this.focusColor,
this.hoverColor,
this.focusNode,
this.autofocus = false,
})
Checkbox 的构造方法同样非常简单
const Checkbox({
Key key,
@required this.value,
this.tristate = false,
@required this.onChanged,
this.mouseCursor,
this.activeColor,
this.checkColor,
this.focusColor,
this.hoverColor,
this.materialTapTargetSize,
this.visualDensity,
this.focusNode,
this.autofocus = false,
})
例子
class _TsmCheckPageState extends State<TsmCheckPage> {
var isSelectSwitch = false;
var isSelectCheckboxIndex = 0;
var check_1 = false;
var check_2 = false;
var check_3 = false;
var check_4 = false;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: Text('勾选框'),
centerTitle: true,
),
body: Container(
color: Colors.white,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Switch(
value: isSelectSwitch,
/// 勾选后颜色
activeColor: Colors.greenAccent,
/// 打开后进度条颜色
activeTrackColor: Colors.blueAccent,
/// 关闭后按钮颜色
inactiveThumbColor: Colors.redAccent,
///关闭后按钮图片
inactiveThumbImage: AssetImage('images/sunny.png'),
onChanged: (isSelect) {
setState(() {
isSelectSwitch = !isSelectSwitch;
});
},
),
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Checkbox(
value: 0 == isSelectCheckboxIndex,
activeColor: Colors.redAccent,
/// 勾选后颜色
onChanged: (isSelect) {
setState(() {
isSelectCheckboxIndex = 0;
});
},
),
Checkbox(
value: 1 == isSelectCheckboxIndex,
activeColor: Colors.blueAccent,
/// 勾选后颜色
onChanged: (isSelect) {
setState(() {
isSelectCheckboxIndex = 1;
});
},
),
Checkbox(
value: 2 == isSelectCheckboxIndex,
activeColor: Colors.purpleAccent,
/// 勾选后颜色
onChanged: (isSelect) {
setState(() {
isSelectCheckboxIndex = 2;
});
},
),
],
),
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Checkbox(
value: check_1,
activeColor: Colors.redAccent,
/// 勾选后颜色
onChanged: (isSelect) {
setState(() {
check_1 = !check_1;
});
},
),
Checkbox(
value: check_2,
activeColor: Colors.blueAccent,
/// 勾选后颜色
onChanged: (isSelect) {
setState(() {
check_2 = !check_2;
});
},
),
Checkbox(
value: check_3,
activeColor: Colors.purpleAccent,
/// 勾选后颜色
onChanged: (isSelect) {
setState(() {
check_3 = !check_3;
});
},
),
Checkbox(
value: check_4,
activeColor: Colors.yellowAccent,
/// 勾选后颜色
onChanged: (isSelect) {
setState(() {
check_4 = !check_4;
});
},
),
],
)
],
),
),
),
);
}
效果图
GIF 2020-8-26 10-00-31.gif
我学习flutter的整个过程都记录在里面了
https://www.jianshu.com/c/36554cb4c804
最后附上demo 地址
网友评论