跨平台开发 / 系统课时

用 ThemeData 统一页面样式

用 ThemeData 统一页面样式

当多个页面都要使用相同的主色、标题字号和按钮外观时,逐个 Widget 设置样式会产生大量重复代码。ThemeData 可以把这些视觉规则集中到应用主题中,让组件自动继承统一样式,同时保留局部覆盖能力。

学习目标

  • 使用 ThemeData 配置应用级颜色和文字样式
  • 使用组件主题统一按钮等常用 Widget 的外观
  • 理解主题继承与局部样式覆盖的优先关系

把公共样式放进 MaterialApp

Flutter 的 Material 应用通常在 MaterialApp 的 theme 属性中提供 ThemeData。这个对象不是单纯的颜色配置,而是一组可以被后代 Material Widget 读取的设计规则。

例如,一个应用有多个页面都需要靛蓝色主题、统一标题字重和圆角按钮,与其在每个 Text、FilledButton 上重复设置,不如只配置一次主题。

下面是一个可以直接运行的完整示例:

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

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        useMaterial3: true,
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.indigo,
        ),
        scaffoldBackgroundColor: Colors.indigo.shade50,
        appBarTheme: const AppBarTheme(
          centerTitle: true,
        ),
        textTheme: const TextTheme(
          titleLarge: TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
          ),
          bodyMedium: TextStyle(
            fontSize: 16,
            height: 1.5,
          ),
        ),
        filledButtonTheme: FilledButtonThemeData(
          style: FilledButton.styleFrom(
            padding: const EdgeInsets.symmetric(
              horizontal: 24,
              vertical: 14,
            ),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        ),
      ),
      home: const HomePage(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    final textTheme = Theme.of(context).textTheme;

    return Scaffold(
      appBar: AppBar(title: const Text('主题示例')),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('今日任务', style: textTheme.titleLarge),
            const SizedBox(height: 8),
            Text(
              '完成页面布局,并检查所有按钮是否保持统一样式。',
              style: textTheme.bodyMedium,
            ),
            const SizedBox(height: 20),
            FilledButton(
              onPressed: () {},
              child: const Text('开始'),
            ),
          ],
        ),
      ),
    );
  }
}

预期结果

text
页面使用浅靛蓝背景;AppBar 标题居中;“今日任务”显示为 24 像素粗体;FilledButton 使用主题统一设置的内边距和 12 像素圆角。

这里的 ColorScheme.fromSeed 根据一个种子颜色生成 Material 配色方案。相比只设置单个主色,颜色方案可以为按钮、背景和其他 Material 组件提供协调的颜色角色。

从主题读取文字样式

配置主题以后,业务页面不必重新声明相同的 TextStyle。通过 Theme.of(context) 可以取得当前 BuildContext 生效的主题,例如:

dart
final textTheme = Theme.of(context).textTheme;

片段示例,需放在拥有有效 BuildContext 的 build 方法或其调用链中。读取主题而不是复制样式值的好处是:以后只修改 ThemeData,所有依赖该主题的页面都会一起变化。

Text 并不会根据内容自动判断它是标题还是正文,因此示例显式选择了 titleLarge 和 bodyMedium。这种写法同时保留了语义:页面代码表达“这是标题”,具体字号和字重则交给主题决定。

用组件主题消除重复配置

ThemeData 还提供针对具体 Material 组件的主题。示例中的 filledButtonTheme 会影响后代的 FilledButton,因此按钮本身不再需要重复编写 padding、shape 等参数。

这种方式尤其适合设计规范明确的项目。例如所有主要操作按钮都使用同一种圆角和尺寸时,应优先配置组件主题;如果只是某一个特殊按钮需要不同外观,再在该按钮上单独设置 style。

理解全局主题和局部覆盖

主题提供的是默认样式,并不会禁止 Widget 自己指定样式。如果某个标题需要特别显示为红色,可以直接覆盖对应属性:

dart
Text(
  '需要处理',
  style: Theme.of(context).textTheme.titleLarge?.copyWith(
        color: Colors.red,
      ),
)

片段示例,需在拥有有效 BuildContext 的 Widget 中使用。这里先继承 titleLarge 的字号和字重,再只改变颜色,比重新创建一整套 TextStyle 更容易保持整体一致。

实际项目中可以遵循一个简单顺序:应用级品牌规则放入 ThemeData,同类组件的共同外观放入组件主题,只有当前 Widget 的特殊差异才在局部覆盖。这样既能统一视觉效果,也不会让页面失去必要的灵活性。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

用 ThemeData 统一页面样式

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通