Flutter基础组件: Switch CheckBox
2022-05-18 本文已影响0人
Roct
Switch
和Checkbox
属性比较简单,读者可以查看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;
});
})
]));
}
}