Skip to content

颜色与字体

颜色和字体是 UI 的基本视觉元素。Flutter 提供了丰富的颜色系统和字体方案,本文将帮你理解它们的使用方式。

颜色

Colors 预设色板

Flutter 的 Colors 类内置了 Material Design 标准色板,涵盖红、蓝、绿、橙、紫等常用色系:

dart
Colors.red           // 红色
Colors.blue          // 蓝色
Colors.green         // 绿色
Colors.orange        // 橙色
Colors.purple        // 紫色
Colors.amber         // 琥珀色
Colors.teal          // 青色
Colors.cyan          // 青蓝色
Colors.pink          // 粉色
Colors.grey          // 灰色
Colors.black         // 黑色
Colors.white         // 白色
Colors.transparent   // 透明

颜色深浅级别

每种颜色都有从 50(最浅)到 900(最深)的深浅级别,数字越大颜色越深。默认值(不带方括号)等同于 [500]

dart
Colors.blue[50]      // 极浅蓝,几乎白色
Colors.blue[100]     // 浅蓝
Colors.blue[200]
Colors.blue[300]
Colors.blue[400]
Colors.blue          // 等同于 Colors.blue[500],标准蓝
Colors.blue[500]     // 标准蓝(默认)
Colors.blue[600]
Colors.blue[700]
Colors.blue[800]
Colors.blue[900]     // 极深蓝,几乎黑色

什么时候用深浅级别?

  • 需要同一色系的视觉层次时:如按钮用 [500],悬停用 [700],禁用用 [200]
  • 区分同色的不同区域:如卡片背景用 [50],标题用 [800]
  • 配合深色/浅色模式:亮色用深色变体,暗色用浅色变体

自定义颜色

当预设色板不满足需求时,可以用以下方式创建自定义颜色:

dart
// 方式 1:ARGB 整数(最常用)
const Color(0xFF42A5F5)         // 0x + AA(透明度) + RR(红) + GG(绿) + BB(蓝)
// FF = 完全不透明,00 = 完全透明
// 42A5F5 = 蓝色的 RGB 值

// 方式 2:RGB + 透明度参数
Color.fromRGBO(66, 165, 245, 1.0)   // R, G, B 各 0~255,透明度 0.0~1.0

// 方式 3:从已有颜色调整透明度
Colors.blue.withOpacity(0.5)         // 50% 透明的蓝色

ARGB 快速解读

0xFF42A5F5 拆解:

  • 0x — 十六进制前缀
  • FF — 透明度(FF = 不透明,80 = 半透明,00 = 全透明)
  • 42A5F5 — RGB 颜色值

常见透明度值:FF(100%)、E6(90%)、CC(80%)、99(60%)、80(50%)、4D(30%)、1A(10%)

颜色工具函数

dart
// 混合两个颜色(0.0 = 完全是第一个,1.0 = 完全是第二个)
Color.lerp(Colors.red, Colors.blue, 0.5)  // 红蓝各半 → 紫色

// 转 HSL 色彩空间(方便调整色相、饱和度、明度)
import 'dart:ui';
final hsl = HSLColor.fromColor(Colors.blue);
final lighter = hsl.withLightness((hsl.lightness + 0.2).clamp(0, 1)).toColor();

在主题中使用颜色(推荐)

在实际项目中,应优先使用主题颜色,而不是硬编码 Colors.xxx。这样深色模式可以自动适配:

dart
import 'package:flutter/material.dart';

class ThemeColorExample extends StatelessWidget {
  const ThemeColorExample({super.key});

  @override
  Widget build(BuildContext context) {
    // ✅ 推荐:使用主题颜色
    // ─── ★ 从主题取颜色 ──────────────
    final colorScheme = Theme.of(context).colorScheme;
    // ─── ☆ 从主题取颜色 ──────────────

    return Scaffold(
      appBar: AppBar(title: const Text('主题颜色示例')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              color: colorScheme.surface,
              padding: const EdgeInsets.all(16),
              child: Text(
                '使用主题颜色的文字',
                style: TextStyle(color: colorScheme.onSurface),
              ),
            ),
            const SizedBox(height: 16),
            // ❌ 不推荐:硬编码颜色(深色模式下可能看不见)
            // Container(color: Colors.white)
            // Text('Hello', style: TextStyle(color: Colors.black))
          ],
        ),
      ),
    );
  }
}

详见 主题(Theme) 文档中的深色模式适配章节。

字体

三种字体使用方式

方式适用场景优缺点
系统默认快速开发,无特殊字体需求零配置,但各平台字体不同
Google Fonts需要统一字体(尤其是中文)跨平台一致,但首次加载需网络
本地自定义字体品牌字体、离线使用完全可控,但增加包体积

系统默认字体

Flutter 默认使用各平台的系统字体:Android 用 Roboto,iOS 用 SF Pro。不需要任何配置。

dart
Text('默认字体')  // 自动使用系统字体

使用 Google Fonts

Google Fonts 包提供了上千种免费字体,对中文开发者来说最重要的是提供了 Noto Sans SC(思源黑体)等中文字体。

安装:

bash
flutter pub add google_fonts

单处使用:

dart
import 'package:google_fonts/google_fonts.dart';

Text(
  '你好世界',
  style: GoogleFonts.notoSansSC(     // 思源黑体简中
    fontSize: 16,
    fontWeight: FontWeight.w500,
  ),
)

全局设置(推荐):

ThemeData 中设置后,整个应用的文字都使用该字体:

dart
MaterialApp(
  theme: ThemeData(
    textTheme: GoogleFonts.notoSansTextTheme(),     // 英文用 Noto Sans
    primaryTextTheme: GoogleFonts.notoSansTextTheme(), // AppBar 等区域
  ),
)

中文字体推荐

google_fonts 包提供了多种中文友好字体:

dart
GoogleFonts.notoSansSC()     // Noto Sans SC(思源黑体)— 最常用
GoogleFonts.notoSerifSC()    // Noto Serif SC(思源宋体)— 正文阅读
GoogleFonts.zcoolKuaiLe()    // 站酷快乐体 — 活泼场景
GoogleFonts.maShanZheng()    // 马善政楷体 — 书法风格

离线使用

Google Fonts 默认从网络下载字体文件。如果需要离线使用,可以在 google_fonts 包的官方文档中查看如何预下载字体文件。

使用本地自定义字体

当需要使用品牌字体或离线运行时,可以将字体文件打包到应用中。

第 1 步: 将字体文件放入 assets/fonts/ 目录

第 2 步:pubspec.yaml 中声明:

yaml
flutter:
  fonts:
    - family: MyFont                    # 字体族名,代码中引用用这个
      fonts:
        - asset: assets/fonts/MyFont-Regular.ttf    # 常规
        - asset: assets/fonts/MyFont-Bold.ttf       # 粗体
          weight: 700                               # 对应 FontWeight.w700
        - asset: assets/fonts/MyFont-Italic.ttf     # 斜体
          style: italic

第 3 步: 使用字体:

dart
// 单处使用
Text('自定义字体', style: TextStyle(fontFamily: 'MyFont'))

// 全局设置
MaterialApp(
  theme: ThemeData(fontFamily: 'MyFont'),
)

字重(FontWeight)

字重控制文字的粗细,从 100(极细)到 900(极粗):

字重值常量名名称常见用途
w100Thin极细大标题装饰
w200ExtraLight特细
w300Light细体辅助文字
w400Regular / Normal常规正文(默认)
w500Medium中等小标题
w600SemiBold半粗强调文字
w700Bold粗体标题(最常用)
w800ExtraBold特粗
w900Black极粗大标题
dart
// 常用写法
TextStyle(fontWeight: FontWeight.normal)   // w400,正文
TextStyle(fontWeight: FontWeight.bold)     // w700,标题
TextStyle(fontWeight: FontWeight.w500)     // Medium,小标题

TextStyle 速查

TextStyle 是控制文字外观的核心类:

dart
const TextStyle(
  fontSize: 16,                         // 字号
  fontWeight: FontWeight.w500,          // 粗细
  color: Colors.black87,                // 颜色
  backgroundColor: Colors.transparent,  // 背景色
  height: 1.5,                          // 行高(倍数,1.5 = 1.5 倍字号)
  letterSpacing: 0.5,                   // 字间距
  wordSpacing: 2,                        // 词间距
  decoration: TextDecoration.underline,  // 下划线
  decorationColor: Colors.red,          // 下划线颜色
  decorationStyle: TextDecorationStyle.solid,
  decorationThickness: 2,               // 下划线粗细
  fontStyle: FontStyle.italic,          // 斜体
  fontFamily: 'MyFont',                 // 字体族
  shadows: [                            // 文字阴影
    Shadow(color: Colors.grey, offset: Offset(1, 1), blurRadius: 2),
  ],
)

使用主题文字样式

在实际项目中,推荐使用 Theme.of(context).textTheme 提供的语义化样式(如 titleLargebodyMedium),而不是手动创建 TextStyle。详见 主题(Theme) 文档。

速查表

场景方案
使用预设颜色Colors.blueColors.red[200]
自定义颜色Color(0xFF42A5F5)
半透明颜色Colors.blue.withOpacity(0.5)
主题颜色(推荐)Theme.of(context).colorScheme.primary
全局字体ThemeData(textTheme: GoogleFonts.xxxTextTheme())
局部字体TextStyle(fontFamily: 'MyFont')
字重FontWeight.normal(w400)、FontWeight.bold(w700)
文字样式优先用 textTheme.titleLarge

基于 Flutter 官方文档整理