Flutter Material3下CheckboxListTile全局主题色设置异常问题
Material3 下可切换组件激活色与文档不符的处理方案
Flutter官方文档明确,Switch、SwitchListTile、Checkbox、CheckboxListTile、Radio、RadioListTile这类可切换组件应使用ColorScheme.secondary作为激活色,且ThemeData.toggleableActiveColor已被废弃。但开启material3: true后,CheckboxListTile实际会使用ColorScheme.primary作为激活色,关闭Material3则符合文档预期。
问题复现代码
主主题配置:
ThemeData( material3 : true, colorScheme: ColorScheme.fromSeed( seedColor: DesignColor.green, primary: DesignColor.green, onPrimary: DesignColor.primaryTextColor, secondary: DesignColor.yellow, onSecondary: DesignColor.white))
CheckboxListTile代码:
CheckboxListTile( controlAffinity: ListTileControlAffinity.leading, title: Text(range999), value: values[1], onChanged: (val) {})
原因分析
这是Material3设计规范的改动导致的:在Material3设计系统中,可切换组件的激活色默认绑定ColorScheme.primary,而Material2中默认使用的是secondary,并非框架bug。
解决方案
如果需要在Material3模式下让这类组件继续使用secondary作为激活色,需通过ThemeData分别为各组件主题指定激活色:
ThemeData( material3: true, colorScheme: ColorScheme.fromSeed( seedColor: DesignColor.green, primary: DesignColor.green, onPrimary: DesignColor.primaryTextColor, secondary: DesignColor.yellow, onSecondary: DesignColor.white, ), // 自定义Checkbox主题 checkboxTheme: CheckboxThemeData( fillColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.selected)) { return Theme.of(context).colorScheme.secondary; } return null; }), ), // 自定义Switch主题 switchTheme: SwitchThemeData( thumbColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.selected)) { return Theme.of(context).colorScheme.secondary; } return null; }), trackColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.selected)) { return Theme.of(context).colorScheme.secondary.withOpacity(0.5); } return null; }), ), // 自定义Radio主题 radioTheme: RadioThemeData( fillColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.selected)) { return Theme.of(context).colorScheme.secondary; } return null; }), ), )
配置完成后,CheckboxListTile、Switch等组件在Material3模式下就会使用secondary颜色作为激活色,与Material2的表现一致。
内容的提问来源于stack exchange,提问作者krishnaacharyaa
相关产品推荐
相关产品推荐

