You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中FontFeature(SMCP)小大写效果异常:显示后消失问题求助

Flutter 文本小大写(small caps)效果仅瞬间显示的解决办法

问题分析

你的代码在DartPad正常工作,但真机/模拟器中效果仅瞬间显示后消失,核心原因是Google Fonts的异步加载机制:

  • DartPad预加载了常用Google字体,初始渲染就能直接使用支持smcp特性的Cardo字体;
  • 真机/模拟器中,Cardo字体是异步下载的,初始渲染会用系统 fallback 字体(多数系统字体不支持small caps),后续字体加载完成后,样式未正确保留fontFeatures配置,导致效果丢失。

解决方案

1. 直接在GoogleFonts构造中传递fontFeatures

将fontFeatures从textStyle中提取,直接作为GoogleFonts.cardo()的参数,确保字体加载完成后特性被正确应用:

Text(
  'This is a Google Font',
  style: GoogleFonts.cardo(
    fontFeatures: [FontFeature.enable('smcp')],
    color: Colors.blue,
    letterSpacing: .5,
  ),
)

2. 预加载字体,避免初始 fallback 字体干扰

在App启动时提前加载Cardo字体,确保渲染时字体已就绪:

void main() async {
  // 预加载Cardo字体
  await GoogleFonts.pendingFonts([GoogleFonts.cardo()]);
  runApp(const MyApp());
}

3. 用FutureBuilder等待字体加载完成

如果不想阻塞App启动,可通过FutureBuilder在字体加载完成后再渲染目标文本:

FutureBuilder(
  future: GoogleFonts.pendingFonts([GoogleFonts.cardo()]),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      return Text(
        'This is a Google Font',
        style: GoogleFonts.cardo(
          fontFeatures: [FontFeature.enable('smcp')],
          color: Colors.blue,
          letterSpacing: .5,
        ),
      );
    }
    // 加载中显示占位文本
    return Text('Loading...', style: TextStyle(color: Colors.blue));
  },
)

验证要点

  • 确认Cardo字体确实支持small caps特性(该字体原生支持smcp,无需额外验证);
  • 检查pubspec.yaml中google_fonts依赖版本是否为最新,旧版本可能存在样式传递的bug。

内容的提问来源于stack exchange,提问作者king mort

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 07:47:23