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

如何在Flutter深浅色主题下设置Text组件的文字颜色

Flutter 深浅主题下Text组件文字颜色适配方法

有两种常用实现方案,按需选择即可:

方案1:全局主题统一配置(推荐,维护成本最低)

直接在应用入口的MaterialApp中分别配置浅色、深色主题的文字样式规则,全局所有Text组件会自动跟随主题切换颜色,不需要给每个组件单独写适配逻辑。

  • 先配置深浅主题的文字样式:
@override
Widget build(BuildContext context) {
  return MaterialApp(
    // 浅色主题配置
    theme: ThemeData(
      brightness: Brightness.light,
      // 全局文字主题配置
      textTheme: const TextTheme(
        titleLarge: TextStyle(color: Color(0xFF1D1D1F)), // 浅色模式下标题类文字用深黑色
        bodyMedium: TextStyle(color: Color(0xFF333333)), // 浅色模式下正文类文字用深灰色
        // 其余文字层级(titleMedium、bodySmall等)按需配置对应颜色即可
      ),
      // 如果是AppBar的标题,也可以单独配置AppBar主题
      appBarTheme: const AppBarTheme(
        titleTextStyle: TextStyle(
          color: Color(0xFF1D1D1F),
          fontSize: 20,
          fontWeight: FontWeight.w500
        )
      )
    ),
    // 深色主题配置
    darkTheme: ThemeData(
      brightness: Brightness.dark,
      textTheme: const TextTheme(
        titleLarge: TextStyle(color: Color(0xFFFFFFFF)), // 深色模式下标题类文字用纯白色
        bodyMedium: TextStyle(color: Color(0xFFE5E5E5)), // 深色模式下正文类文字用浅灰色
      ),
      appBarTheme: const AppBarTheme(
        titleTextStyle: TextStyle(
          color: Color(0xFFFFFFFF),
          fontSize: 20,
          fontWeight: FontWeight.w500
        )
      )
    ),
    // 主题切换规则:跟随系统自动切换,也可手动指定ThemeMode.light/ThemeMode.dark
    themeMode: ThemeMode.system,
    home: const MyHomePage(),
  );
}
  • 配置完成后,原有代码不需要做任何修改,直接使用即可自动适配:
title: Text('Kitchen Name')

方案2:单独给指定Text组件做适配

如果只有少量Text组件需要自定义颜色,不需要修改全局配置,可以在组件内直接判断当前主题模式,单独设置颜色:

title: Text(
  'Kitchen Name',
  style: TextStyle(
    // 判断当前是否为深色模式,返回对应颜色
    color: Theme.of(context).brightness == Brightness.dark
        ? Colors.white
        : Colors.black87
  ),
)

注意:如果给Text手动设置了style属性,只要style里没有硬编码color参数,组件依然会自动继承全局主题配置的文字颜色,只有硬编码写了color值才会覆盖全局规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 11:42:23