蓝色天空网mbsky.com · 知识 · 实践 · 创造Flutter · 本地阅读预览
教程 / 移动开发 / Flutter

Flutter 主题与样式

系统掌握 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 离线核验

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 验证全局组件子主题、primary/onPrimary 成对语义色与局部覆写、ThemeMode 三态切换及 57..11 单调递减字阶体系。
运行 Material 3 ThemeData 配置、ColorScheme 令牌继承、ThemeMode 切换与 15 级 TextTheme 离线核验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:f4b4c57bd13655c8f9d1f1de88ed8472981cec8a10af545f38a47968a7644b23

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Flutter 主题与样式实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:e3c23aeb96672199de3bf7eab2eac9055a2819937432dd67c704deeae1561b9d

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么不能直接调用 `Theme.of(context).setThemeMode(...)` 来切换深色模式?正确做法是什么?

展开参考解答

`Theme.of(context)` 返回的是不可变的 `ThemeData` 快照对象,并不提供修改全局模式的方法;正确做法是在 `MaterialApp` 上层维护 `ThemeMode` 状态(如 `ValueNotifier<ThemeMode>` 或 `Provider`),通过更新该状态重新向 `MaterialApp.themeMode` 传值。

规范与官方依据