Flutter使用google_fonts时copyWith修改fontWeight效果与官方展示不一致问题
问题原因
字体粗细显示异常是google_fonts包的加载逻辑导致的:GoogleFonts.xxx()方法仅会在首次调用时,加载你指定fontWeight参数对应的字体文件。而通过copyWith修改已有GoogleFonts样式的fontWeight属性时,仅会修改TextStyle的属性值,不会触发对应字重字体文件的加载,Flutter只能使用默认字体的伪粗/伪细效果渲染,自然和Google Fonts官方效果不一致。
解决方法
- 不要在GoogleFonts生成的样式上用
copyWith修改字重,需要不同字重的Lato样式时,单独调用GoogleFonts.lato()指定对应fontWeight生成独立样式,示例如下:
class AppTextStyles { // 每个字重单独声明,触发对应字体文件加载 static TextStyle latoW100 = GoogleFonts.lato(fontWeight: FontWeight.w100, fontSize: 33, color: Colors.black); static TextStyle latoW200 = GoogleFonts.lato(fontWeight: FontWeight.w200, fontSize: 33, color: Colors.black); static TextStyle latoW300 = GoogleFonts.lato(fontWeight: FontWeight.w300, fontSize: 33, color: Colors.black); // 其余字重以此类推 }
- 如果你需要预加载所有用到的Lato字重,避免首次显示时加载延迟,可以在应用启动时提前注册对应字体:
void main() async { // 预加载所有你需要用到的Lato字重 GoogleFonts.registerLatoFont( weights: [FontWeight.w100, FontWeight.w200, FontWeight.w300, FontWeight.w400, FontWeight.w500, FontWeight.w600, FontWeight.w700, FontWeight.w800, FontWeight.w900], ); runApp(const MyApp()); }
- Web端如果出现字体切换有延迟,可以等待字体加载完成后再渲染对应文字:
// 等待字体加载完成前显示页面 await GoogleFonts.pendingFonts([ GoogleFonts.lato(fontWeight: FontWeight.w100), GoogleFonts.lato(fontWeight: FontWeight.w700), // 其余需要加载的字体样式 ]);
内容的提问来源于stack exchange,提问作者Md. Yeasin Sheikh
相关产品推荐
相关产品推荐

