Flutter switch 开关组件浅析
前言
在日常开发中,switch 开关组件,也是比较常用的组件的,本篇文章将记录switch 简单使用及属性。
Switch 组件的属性
我们先来看一下 Switch 组件的源码
const Switch({
super.key,
required this.value,
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,
})
从上面源码中,我们可以看到 Switch 有非常多的属性,下面来介绍一下常用的属性
- activeColor: Color - 激活时原点的颜色。
- activeThumbImage: ImageProvider - 原点还支持图片,激活时的效果。
- activeTrackColor: Color - 激活时横条的颜色。
- inactiveThumbColor: Color - 非激活时原点的颜色。
- inactiveThumbImage: ImageProvider - 非激活原点的图片效果。
- inactiveTrackColor: Color - 非激活时横条的颜色。
- onChanged: ValueChanged - 改变时触发。
- value: → bool - 切换按钮的值。
需要说明的是,Switch 有一个变体 adaptive,也是我们最常用的一个变体:
Switch.adaptive(value: model.isSwitch, onChanged: (value){
print(value);
model.isSwitch = value;
model.notifyListeners();
}),
使用效果:
总结
本篇文章就简单的记录到这里,比较简单,我们主要记住 Switch.adaptive 这个变体,就可以了。