Flutter中随系统主题切换时自定义文本颜色不生效的解决方法
解决Flutter自定义TextTheme随系统主题动态切换颜色的问题
问题根源
你当前的核心问题出在自定义d1 TextStyle的颜色判断逻辑上:
Brightness.dark == null这种写法完全错误,Brightness.dark是枚举常量,永远不会等于null,导致你的文本颜色被固定为Colors.white,自然不会随主题切换变化。- 你没有关联当前上下文的实际主题亮度,相当于完全脱离了系统主题的状态来设置颜色。
修复方案
这里提供两种简洁的实现方式,都能让文本颜色跟随系统主题动态调整:
方式一:使用时结合当前主题亮度动态设置(快速修改)
先修改text_themes.dart,去掉错误的固定颜色,只保留基础样式:
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; extension CustomTextStyles on TextTheme { TextStyle get h1 { return TextStyle( fontSize: 24.0, fontWeight: FontWeight.bold, ); } // 仅定义基础样式,不固定颜色 TextStyle get d1Base { return TextStyle( fontSize: 16.0, fontWeight: FontWeight.bold, ); } TextStyle get d2 { return TextStyle(fontSize: 16.0); } }
然后在home_screen.dart中使用时,通过Theme.of(context)获取当前主题亮度,动态设置颜色:
child: Row( children: <Widget>[ Container( child: Text( 'Email Id : ', style: Theme.of(context).textTheme.d1Base.copyWith( color: Theme.of(context).brightness == Brightness.dark ? Colors.white : Colors.blue[800], ), ), ), Container( child: Text( 'user1@gmail.com', style: Theme.of(context).textTheme.d2, overflow: TextOverflow.ellipsis, ), ), ], ),
方式二:扩展方法接收亮度参数(更优雅)
如果不想每次使用都写copyWith,可以给扩展方法增加参数,直接返回适配当前主题的样式:
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; extension CustomTextStyles on TextTheme { TextStyle get h1 { return TextStyle( fontSize: 24.0, fontWeight: FontWeight.bold, ); } // 接收Brightness参数,动态生成对应颜色的样式 TextStyle d1(Brightness brightness) { return TextStyle( fontSize: 16.0, fontWeight: FontWeight.bold, color: brightness == Brightness.dark ? Colors.white : Colors.blue[800], ); } TextStyle get d2 { return TextStyle(fontSize: 16.0); } }
使用时传入当前主题的亮度即可:
child: Row( children: <Widget>[ Container( child: Text( 'Email Id : ', style: Theme.of(context).textTheme.d1(Theme.of(context).brightness), ), ), Container( child: Text( 'user1@gmail.com', style: Theme.of(context).textTheme.d2, overflow: TextOverflow.ellipsis, ), ), ], ),
额外验证
你的MaterialApp配置是正确的:已经设置了theme(浅色主题)和darkTheme(深色主题),且未手动指定themeMode,Flutter会自动跟随系统主题模式,这部分无需修改。
现在切换系统的明暗模式,文本颜色应该就能正常同步变化了。
内容的提问来源于stack exchange,提问作者Atharva Pradhan
相关产品推荐
相关产品推荐

