Flutter明暗模式切换场景下如何访问ThemeData的primarySwatch色值
方案1:Material2场景直接调用(最简实现)
只要你在明/暗两套ThemeData初始化时都传入对应primarySwatch参数,Flutter原生ThemeData本身已经公开了primarySwatch属性,可直接调用获取对应色值:
// 亮色主题按相同规则配置 get lightTheme => ThemeData( primaryColor: lightSwatch.shade50, primarySwatch: lightSwatch, ); // 业务层直接调用,无需手动判断亮度 Container( color: Theme.of(context).primarySwatch.shade100, )
如果上述方法拿不到预期值,大概率是你开启了Material3样式:Material3模式下primarySwatch参数会被用于自动生成ColorScheme,不会直接赋值给ThemeData.primarySwatch属性,这时候用方案2即可。
方案2:Material3场景自定义ThemeExtension(扩展性最高)
通过自定义主题扩展类封装自定义色板,明/暗主题分别注入对应色板实例,后续可以灵活扩展更多自定义颜色规则:
- 定义自定义色板扩展类
@immutable class CustomSwatch extends ThemeExtension<CustomSwatch> { final MaterialColor primarySwatch; const CustomSwatch({required this.primarySwatch}); @override CustomSwatch copyWith({MaterialColor? primarySwatch}) { return CustomSwatch( primarySwatch: primarySwatch ?? this.primarySwatch, ); } @override CustomSwatch lerp(ThemeExtension<CustomSwatch>? other, double t) { if (other is! CustomSwatch) return this; return CustomSwatch( primarySwatch: MaterialColor.lerp(primarySwatch, other.primarySwatch, t) ?? primarySwatch, ); } }
- 注入到明暗主题配置
get darkTheme => ThemeData( useMaterial3: true, // 原有主题配置保持不变 extensions: const [ CustomSwatch(primarySwatch: darkSwatch), ], ); get lightTheme => ThemeData( useMaterial3: true, // 原有主题配置保持不变 extensions: const [ CustomSwatch(primarySwatch: lightSwatch), ], );
- 业务层调用
Container( color: Theme.of(context).extension<CustomSwatch>()!.primarySwatch.shade100, )
你可以将所有自定义色板都放到该扩展类中,后续新增自定义颜色不需要修改ThemeData原生属性,维护成本更低。
内容的提问来源于stack exchange,提问作者Edblocker
相关产品推荐
相关产品推荐

