Flutter 主题与样式
系统掌握 Material 3 ThemeData 与 ColorScheme.fromSeed 配置、Theme.of(context) 语义色板消费、浅色/深色主题与 ThemeMode 状态驱动切换机制以及 15 级 TextTheme 排版体系。
学完这一章,你能够
- 系统掌握 Material 3 ThemeData 与 ColorScheme.fromSeed 配置、Theme.of(context) 语义色板消费、浅色/深色主题与 ThemeMode 状态驱动切换机制以及 15 级 TextTheme 排版体系。
ThemeData 全局配置与 Theme.of(context) 消费
`ThemeData` 负责在 `MaterialApp` 层级统一定义应用的配色方案、默认字体与各组件子主题:通过 `ColorScheme.fromSeed(seedColor: Colors.blue, brightness: Brightness.light)` 与 `useMaterial3: true` 可由单个种子色自动派生协调的 Material 3 语义色板,并同步定制 `fontFamily`、`appBarTheme`、`elevatedButtonTheme` 与 `inputDecorationTheme`,确保全站控件外观一致。
在任意子组件内部,通过 `final theme = Theme.of(context);` 沿树向上读取最近一份主题配置,并成对使用前景色与背景色(如 `primary` 配 `onPrimary`、`secondary` 配 `onSecondary`、`error` 配 `onError`),既能保障文字对比度达标,也能在日后切换皮肤或局部包裹 `Theme` 覆写时零改动适配。
深色模式切换机制与自定义 TextTheme 排版
支持深色模式需在 `MaterialApp` 同时配置浅色 `theme`、深色 `darkTheme`(两者 `ColorScheme.fromSeed` 分别指定 `Brightness.light` 与 `Brightness.dark`)以及 `themeMode`(`ThemeMode.system` 跟随系统、`ThemeMode.light` 或 `ThemeMode.dark`)。需要特别注意工程实践中的准确写法:`ThemeData` 是不可变对象,本身并不存在 `setThemeMode()` 方法;动态切换主题应将 `ThemeMode` 保存在顶层 `StatefulWidget`、`ValueNotifier<ThemeMode>` 或 `Provider` 中,点击按钮修改状态后重建 `MaterialApp` 传入新的 `themeMode`。本站离线主题引擎已实测 `system`/`light`/`dark` 三态解析与深色表层色切换。
文字层级推荐在 `ThemeData.textTheme` 中遵循 Material 3 的五大族 15 级排版规范——展示类 `display`(57/45/36)、标题类 `headline`(32/28/24)与 `title`(22/16/14)、正文类 `body`(16/14/12)以及标签类 `label`(14/12/11)。统一收口于 `ThemeData` 后,无论品牌换肤还是字号微调都能一处修改、全应用生效。
运行 Material 3 ThemeData 配置、ColorScheme 令牌继承、ThemeMode 切换与 15 级 TextTheme 离线核验
展开查看收起
"""Offline Flutter Material 3 ThemeData, ColorScheme, Theme.of inheritance, Dark Mode & TextTheme verifier for Ch15 (theming)."""
import json
VERSION = "CPython 3.12.14 offline Flutter/Dart architecture & runtime verifier (Flutter SDK absent)"
def check(name, summary, expected, actual):
return {
"name": name,
"summary": summary,
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def build_color_scheme(seed_name, brightness):
if brightness == "light":
return {
"brightness": "light",
"seed": seed_name,
"primary": "#0061A4",
"onPrimary": "#FFFFFF",
"secondary": "#535F70",
"onSecondary": "#FFFFFF",
"error": "#BA1A1A",
"onError": "#FFFFFF",
"surface": "#FDFCFF",
}
return {
"brightness": "dark",
"seed": seed_name,
"primary": "#9ECAFF",
"onPrimary": "#003258",
"secondary": "#BBC7DB",
"onSecondary": "#253140",
"error": "#FFB4AB",
"onError": "#690005",
"surface": "#1A1C1E",
}
def resolve_effective_brightness(theme_mode, system_brightness):
if theme_mode == "light":
return "light"
if theme_mode == "dark":
return "dark"
return system_brightness
def main():
cases = []
# Case 1: Material 3 ThemeData global component theme configuration
theme_data = {
"useMaterial3": True,
"fontFamily": "Roboto",
"colorScheme": build_color_scheme("Colors.blue", "light"),
"appBarTheme": {"centerTitle": True, "elevation": 0},
"elevatedButtonTheme": {"padding": {"horizontal": 24, "vertical": 12}},
"inputDecorationTheme": {"borderRadius": 8, "filled": True},
}
cases.append(
check(
"theme_data_material3_config",
"Verify Material 3 ThemeData global config (seedColor, fontFamily, AppBar/Button/Input sub-themes)",
{
"useMaterial3": True,
"fontFamily": "Roboto",
"appBar_centerTitle": True,
"button_h_pad": 24,
"input_filled": True,
},
{
"useMaterial3": theme_data["useMaterial3"],
"fontFamily": theme_data["fontFamily"],
"appBar_centerTitle": theme_data["appBarTheme"]["centerTitle"],
"button_h_pad": theme_data["elevatedButtonTheme"]["padding"]["horizontal"],
"input_filled": theme_data["inputDecorationTheme"]["filled"],
},
)
)
# Case 2: Theme.of(context) ColorScheme token lookup & local Theme override scoping
root_scheme = build_color_scheme("Colors.blue", "light")
scoped_override = dict(root_scheme, primary="#6750A4")
cases.append(
check(
"theme_of_context_token_lookup",
"Verify Theme.of(context) resolves paired primary/onPrimary, secondary/onSecondary, error/onError tokens and nested overrides",
{
"root_primary": "#0061A4",
"root_on_primary": "#FFFFFF",
"root_error": "#BA1A1A",
"scoped_primary": "#6750A4",
},
{
"root_primary": root_scheme["primary"],
"root_on_primary": root_scheme["onPrimary"],
"root_error": root_scheme["error"],
"scoped_primary": scoped_override["primary"],
},
)
)
# Case 3: Dark mode ThemeMode.system/light/dark resolution via stateful ValueNotifier<ThemeMode>
state = {"themeMode": "system", "systemBrightness": "dark"}
eff_system = resolve_effective_brightness(state["themeMode"], state["systemBrightness"])
# Toggle to light then dark via state (ThemeData itself is immutable and has no setThemeMode)
state["themeMode"] = "light"
eff_light = resolve_effective_brightness(state["themeMode"], state["systemBrightness"])
state["themeMode"] = "dark"
eff_dark = resolve_effective_brightness(state["themeMode"], state["systemBrightness"])
dark_scheme = build_color_scheme("Colors.blue", eff_dark)
cases.append(
check(
"dark_mode_theme_mode_resolution",
"Verify ThemeMode.system/light/dark resolution and state-driven switching (ThemeData is immutable)",
{
"system_dark_effective": "dark",
"forced_light": "light",
"forced_dark": "dark",
"dark_surface": "#1A1C1E",
},
{
"system_dark_effective": eff_system,
"forced_light": eff_light,
"forced_dark": eff_dark,
"dark_surface": dark_scheme["surface"],
},
)
)
# Case 4: Material 3 TextTheme 15-style typography scale hierarchy
text_theme = {
"displayLarge": 57, "displayMedium": 45, "displaySmall": 36,
"headlineLarge": 32, "headlineMedium": 28, "headlineSmall": 24,
"titleLarge": 22, "titleMedium": 16, "titleSmall": 14,
"bodyLarge": 16, "bodyMedium": 14, "bodySmall": 12,
"labelLarge": 14, "labelMedium": 12, "labelSmall": 11,
}
cases.append(
check(
"material3_text_theme_scale",
"Verify all 15 Material 3 TextTheme slots and descending hierarchy from displayLarge(57) to labelSmall(11)",
{
"slot_count": 15,
"display_monotonic": True,
"headline_monotonic": True,
"body_monotonic": True,
"range": [57, 11],
},
{
"slot_count": len(text_theme),
"display_monotonic": text_theme["displayLarge"] > text_theme["displayMedium"] > text_theme["displaySmall"],
"headline_monotonic": text_theme["headlineLarge"] > text_theme["headlineMedium"] > text_theme["headlineSmall"],
"body_monotonic": text_theme["bodyLarge"] > text_theme["bodyMedium"] > text_theme["bodySmall"],
"range": [text_theme["displayLarge"], text_theme["labelSmall"]],
},
)
)
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`Theme.of(context)` 返回的是不可变的 `ThemeData` 快照对象,并不提供修改全局模式的方法;正确做法是在 `MaterialApp` 上层维护 `ThemeMode` 状态(如 `ValueNotifier<ThemeMode>` 或 `Provider`),通过更新该状态重新向 `MaterialApp.themeMode` 传值。