Switch
Switch为material风格的开关组件,基本用法如下:
var _switchValue = false;
_buildSwitch(){
return Switch(
value: _switchValue,
onChanged: (value){
setState(() {
_switchValue = value;
});
},
);
}
效果如下:
设置激活状态下thumb及track颜色,用法如下:
Switch(
activeColor: Colors.red,
activeTrackColor: Colors.blue,
...
)
效果如下:

注意红色区域为thumb,蓝色区域为track。
thumb区域也可以设置图片,用法如下:
Switch(
activeThumbImage: AssetImage('images/bird.png',),
...
)
效果如下:
有激活状态样式的设置,也有未激活样式的设置,用法如下:
Switch(
inactiveThumbColor: Colors.black54,
inactiveThumbImage: AssetImage('images/bird.png',),
inactiveTrackColor: Colors.blue,
...
)
#SwitchListTile
SwitchListTile是Switch和ListTile组合控件,基本用法如下:
var _switchValue = false;
_buildSwitch(){
return SwitchListTile(
title:Text('是否允许4G下载'),
value: _switchValue,
onChanged: (value){
setState(() {
_switchValue = value;
});
},
);
}
效果如下:
所有的属性都是Switch和ListTile属性的组合,可到具体控件查看其属性。
#CupertinoSwitch
CupertinoSwitch是ios风格控件,用法和Switch一样,用法如下:
var _switchValue = false;
_buildSwitch(){
return CupertinoSwitch(
value: _switchValue,
onChanged: (value){
setState(() {
_switchValue = value;
});
},
);
}
效果如下:
代码:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/**
* Switch 开关组件
*/
class SwitchDemo extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return SwitchDemoState();
}
}
class SwitchDemoState extends State<SwitchDemo> {
// true 表示关 false 表示开
var _switchValue = true;
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: [
Switch(
value: _switchValue,
activeColor: Colors.red, // 激活状态下的颜色
activeTrackColor: Colors.blue, // 激活状态下的颜色
onChanged: (value) {
setState(() {
_switchValue = value;
});
}
),
SwitchListTile(
title: Text("是否打开"),
value: _switchValue,
onChanged: (value) {
setState(() {
_switchValue = value;
});
},
),
CupertinoSwitch(
value: _switchValue,
onChanged: (value) {
setState(() {
_switchValue = value;
});
}
)
],
),
);
}
}

网友评论