如何優(yōu)雅的改變Flutter中CheckBox未選中狀態(tài)下的顏色
起因
很早在做Demo的時(shí)候就想改變下CheckBox的未選中狀態(tài)的顏色,但是多是設(shè)置全局ThemeData.unselectedWidgetColor的顏色來(lái)設(shè)置。
不過(guò)可以想到的就是一個(gè)App中如果有不同顏色的變態(tài)需求的話......??。
解決方法
一. 當(dāng)然是自己重寫(xiě)Widget就好了,不過(guò)稍有點(diǎn)復(fù)雜。放棄了,等后面有時(shí)間來(lái)弄下吧。
二. 想想覺(jué)得不會(huì)設(shè)計(jì)的這么差吧,就追了下源碼。
-
既然可以通過(guò)
ThemeData.unselectedWidgetColor設(shè)置,那么CheckBox中肯定會(huì)用到咯。// 第一處搜索到的 /// {@template flutter.material.checkbox.fillColor} /// The color that fills the checkbox, in all [MaterialState]s. /// /// Resolves in the following states: /// * [MaterialState.selected]. /// * [MaterialState.hovered]. /// * [MaterialState.focused]. /// * [MaterialState.disabled]. /// {@endtemplate} /// /// If null, then the value of [activeColor] is used in the selected /// state. If that is also null, the value of [CheckboxThemeData.fillColor] /// is used. If that is also null, then [ThemeData.disabledColor] is used in /// the disabled state, [ThemeData.toggleableActiveColor] is used in the /// selected state, and [ThemeData.unselectedWidgetColor] is used in the /// default state. final MaterialStateProperty<Color?>? fillColor; // 第二處搜索到的 MaterialStateProperty<Color> get _defaultFillColor { final ThemeData themeData = Theme.of(context); return MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return themeData.disabledColor; } if (states.contains(MaterialState.selected)) { return themeData.toggleableActiveColor; } return themeData.unselectedWidgetColor; // 就是這里返回了 }); } 既然
fillColor中默認(rèn)狀態(tài)下使用了unselectedWidgetColor,那么直接設(shè)置其為自定義顏色不就完了。但是很顯然
fillColor返回的對(duì)象是MaterialStateProperty<Color?>?, 看名字不就是一個(gè)配置文件嘛。只要按照_defalutFilllColor寫(xiě)不就好了。
Checkbox(
value: false,
fillColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
const Set<MaterialState> interactiveStates = <MaterialState>{
MaterialState.pressed,
MaterialState.hovered,
MaterialState.focused,
};
if (states.contains(MaterialState.disabled)) {
return ThemeData.from(colorScheme: ColorScheme.light()).disabledColor;
}
if (states.contains(MaterialState.selected)) {
return ThemeData().toggleableActiveColor;
}
if (states.any(interactiveStates.contains)) {
return Colors.red;
}
// 最終返回
return Colors.blue;
}),
onChanged: (value) {
},
),
- 完工,這樣就不要去設(shè)置全局變量,可以在每個(gè)CheckBox設(shè)置不同的顏色了。??