Skip to content

Flutter 国际化与主题 ​

国际化(i18n)和主题(Theme)是工程化项目的两大基础设施。一次配好,后面增删语言、切换暗黑都是分钟级。


一、国际化:官方 flutter_localizations + l10n ​

Flutter 官方推荐方案,基于 ARB(Application Resource Bundle)。

安装 ​

pubspec.yaml:

yaml
dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  intl: any

flutter:
  generate: true       # ⚠️ 必须开启代码生成

根目录新建 l10n.yaml:

yaml
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart

写翻译 ​

lib/l10n/app_en.arb:

json
{
  "@@locale": "en",
  "hello": "Hello",
  "@hello": { "description": "打招呼" },
  "greeting": "Hello, {name}!",
  "@greeting": {
    "placeholders": {
      "name": { "type": "String" }
    }
  },
  "itemsCount": "{count, plural, =0{No items} =1{1 item} other{{count} items}}",
  "@itemsCount": {
    "placeholders": {
      "count": { "type": "int" }
    }
  }
}

lib/l10n/app_zh.arb:

json
{
  "@@locale": "zh",
  "hello": "你好",
  "greeting": "你好,{name}!",
  "itemsCount": "{count, plural, =0{没有项} other{{count} 项}}"
}

配置 MaterialApp ​

dart
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

MaterialApp(
  localizationsDelegates: AppLocalizations.localizationsDelegates,
  supportedLocales: AppLocalizations.supportedLocales,
  // 不指定时跟随系统;指定就强制
  locale: const Locale('zh'),
  ...
)

使用 ​

dart
final l = AppLocalizations.of(context)!;

Text(l.hello)                          // "你好"
Text(l.greeting('张三'))               // "你好,张三!"
Text(l.itemsCount(0))                  // "没有项"
Text(l.itemsCount(5))                  // "5 项"

flutter gen-l10n 或运行项目时自动生成 AppLocalizations 类,强类型 + IDE 补全。


二、复数 / 选择 / 性别(ICU 语法) ​

plural ​

json
"items": "{count, plural, =0{无} =1{一项} other{{count} 项}}"

select ​

json
"role": "{role, select, admin{管理员} user{用户} other{未知}}"
dart
l.role('admin')   // "管理员"

嵌套:复数 + 性别 ​

json
"msg": "{gender, select, male{他买了 {count, plural, =1{一本书} other{{count} 本书}}} female{她...} other{...}}"

ICU 语法功能强,但写复杂了一行 ARB 反而难读。保持简单,复杂的逻辑拆多个 key。


三、动态切换语言 ​

用 Riverpod / Provider 存当前 Locale ​

dart
final localeProvider = StateProvider<Locale>((_) => const Locale('zh'));

// MaterialApp 里
MaterialApp(
  locale: ref.watch(localeProvider),
  localizationsDelegates: AppLocalizations.localizationsDelegates,
  supportedLocales: AppLocalizations.supportedLocales,
  ...
)

// 切换
ref.read(localeProvider.notifier).state = const Locale('en');

切完整个 App 自动重新构建,所有翻译跟着变。

持久化用户选择 ​

dart
final prefs = await SharedPreferences.getInstance();
final saved = prefs.getString('locale') ?? 'zh';

// 保存
await prefs.setString('locale', 'en');

回顾 14:用 SharedPreferences 存配置。


四、日期 / 数字 / 货币本地化 ​

intl 包帮你格式化:

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

DateFormat.yMd(Locale.toLanguageTag()).format(DateTime.now());
// en: 5/2/2026  zh: 2026/5/2  ja: 2026/05/02

NumberFormat.currency(locale: 'zh', symbol: '¥').format(1234567.89);
// "¥1,234,567.89"

NumberFormat.percentPattern('en').format(0.45);
// "45%"

记得在 main 里初始化:

dart
await initializeDateFormatting();

五、其他常用 i18n 库 ​

库特点
easy_localization用 JSON 文件,API 简洁,生态好
slang强类型 + 代码生成,做得最完善
GetX i18n跟 GetX 绑定,极简

不强求,官方 l10n 完全够用。


六、主题:ThemeData 全局样式 ​

最简 ​

dart
MaterialApp(
  theme: ThemeData.light(useMaterial3: true),
  darkTheme: ThemeData.dark(useMaterial3: true),
  themeMode: ThemeMode.system,    // light / dark / system
  home: const HomePage(),
)

ThemeMode.system 会跟随系统暗黑模式。

自定义品牌色(Material 3 推荐) ​

dart
ThemeData(
  useMaterial3: true,
  colorScheme: ColorScheme.fromSeed(
    seedColor: const Color(0xFF6750A4),
    brightness: Brightness.light,
  ),
)

fromSeed 自动生成完整调色板(主色、次色、背景、表面、错误等),保证设计一致。

用主题 ​

dart
final theme = Theme.of(context);

Container(
  color: theme.colorScheme.primary,
  child: Text(
    'Hello',
    style: theme.textTheme.titleLarge,
  ),
)

回顾 04:Theme.of(context) 自动订阅,主题切换 UI 自动重建。


七、亮色 / 暗色 / 跟随系统 ​

dart
final themeProvider = StateProvider<ThemeMode>((_) => ThemeMode.system);

MaterialApp(
  themeMode: ref.watch(themeProvider),
  theme: lightTheme,
  darkTheme: darkTheme,
)

// 切换
ref.read(themeProvider.notifier).state = ThemeMode.dark;

一套 ColorScheme 自动出亮 / 暗 ​

dart
final lightTheme = ThemeData(
  useMaterial3: true,
  colorScheme: ColorScheme.fromSeed(
    seedColor: Colors.blue,
    brightness: Brightness.light,
  ),
);

final darkTheme = ThemeData(
  useMaterial3: true,
  colorScheme: ColorScheme.fromSeed(
    seedColor: Colors.blue,
    brightness: Brightness.dark,
  ),
);

八、ThemeExtension:自定义主题字段 ​

主题预定义字段(primary、surface 等)不够用,加自己的:

dart
class AppColors extends ThemeExtension<AppColors> {
  final Color brand;
  final Color success;

  const AppColors({required this.brand, required this.success});

  @override
  AppColors copyWith({Color? brand, Color? success}) =>
      AppColors(brand: brand ?? this.brand, success: success ?? this.success);

  @override
  AppColors lerp(AppColors? other, double t) =>
      AppColors(
        brand: Color.lerp(brand, other?.brand, t)!,
        success: Color.lerp(success, other?.success, t)!,
      );
}

// 注册
ThemeData(
  extensions: [
    const AppColors(brand: Color(0xFFFF6B6B), success: Color(0xFF4ECDC4)),
  ],
)

// 使用
final c = Theme.of(context).extension<AppColors>()!;
Container(color: c.brand);

切主题时自动 lerp(平滑过渡)。


九、文字样式系统 ​

dart
ThemeData(
  textTheme: const TextTheme(
    displayLarge: TextStyle(fontSize: 57, fontWeight: FontWeight.w400),
    headlineLarge: TextStyle(fontSize: 32, fontWeight: FontWeight.w400),
    titleLarge: TextStyle(fontSize: 22, fontWeight: FontWeight.w500),
    bodyLarge: TextStyle(fontSize: 16),
    bodyMedium: TextStyle(fontSize: 14),
    labelLarge: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
  ),
)

// 用
Text('标题', style: theme.textTheme.titleLarge);

别在每个 Text 里写 fontSize、color,主题统一管理。


十、字体配置 ​

pubspec.yaml:

yaml
flutter:
  fonts:
    - family: Inter
      fonts:
        - asset: assets/fonts/Inter-Regular.ttf
        - asset: assets/fonts/Inter-Bold.ttf
          weight: 700
    - family: 黑体
      fonts:
        - asset: assets/fonts/SourceHanSans-Regular.otf
dart
ThemeData(
  fontFamily: 'Inter',
)

Text('混排:中文 + English',
  style: TextStyle(fontFamilyFallback: ['Inter', '黑体']),
)

中英混排时设 fontFamilyFallback,中文 fallback 到中文字体。

Google Fonts(在线 / 缓存) ​

yaml
dependencies:
  google_fonts: ^6.2.1
dart
import 'package:google_fonts/google_fonts.dart';

ThemeData(
  textTheme: GoogleFonts.interTextTheme(),
)

第一次下载,后续从缓存读。


十一、组件级覆盖 ​

主题里给特定组件统一外观:

dart
ThemeData(
  appBarTheme: const AppBarTheme(
    centerTitle: true,
    elevation: 0,
  ),
  elevatedButtonTheme: ElevatedButtonThemeData(
    style: ElevatedButton.styleFrom(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      minimumSize: const Size.fromHeight(48),
    ),
  ),
  inputDecorationTheme: const InputDecorationTheme(
    border: OutlineInputBorder(),
    contentPadding: EdgeInsets.all(12),
  ),
)

后面所有 AppBar / ElevatedButton / TextField 自动统一。


十二、Material 3 概览 ​

Flutter 3.16+ 默认 useMaterial3: true。和 Material 2 的主要差异:

Material 2Material 3
primary / accentprimary / secondary / tertiary
灰色阴影表面层级 + tonal 颜色
圆角 4px圆角 12-28px(更圆)
导航偏 ToolBar导航更突出(NavigationBar / NavigationRail)
字体偏紧凑字号更大 / 行距更宽

新组件:NavigationBar、NavigationDrawer、SegmentedButton、SearchBar、MenuAnchor。 新项目直接用 M3,不用考虑 M2。


十三、自适应:Cupertino 风格 ​

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

CupertinoApp(
  theme: CupertinoThemeData(
    primaryColor: CupertinoColors.activeBlue,
  ),
)

或同一 App 里按平台自适应:

dart
Platform.isIOS
  ? CupertinoButton(...)
  : ElevatedButton(...)

或用 flutter_platform_widgets 包统一 API:

dart
PlatformElevatedButton(child: Text('OK'), onPressed: () {})

iOS 上自动渲染成 CupertinoButton,Android 上 ElevatedButton。


十四、暗黑模式适配 tips ​

  1. 用 theme.colorScheme.xxx,别写死颜色

    dart
    color: Colors.white            // ❌ 暗黑下会瞎
    color: theme.colorScheme.surface  // ✅
  2. 图片有亮 / 暗版本

    dart
    Image.asset(
      theme.brightness == Brightness.dark
        ? 'assets/logo_dark.png'
        : 'assets/logo_light.png',
    )
  3. 状态栏跟随主题

    dart
    SystemChrome.setSystemUIOverlayStyle(
      theme.brightness == Brightness.dark
        ? SystemUiOverlayStyle.light
        : SystemUiOverlayStyle.dark,
    );

十五、响应式 / 屏幕适配 ​

dart
final size = MediaQuery.of(context).size;
final isTablet = size.width >= 600;

或 LayoutBuilder:

dart
LayoutBuilder(builder: (_, constraints) {
  if (constraints.maxWidth > 600) return TabletLayout();
  return PhoneLayout();
})

flutter_screenutil 用于设计稿尺寸自动转换:

dart
ScreenUtilInit(
  designSize: const Size(375, 812),
  builder: (_, __) => MaterialApp(...),
)

// 用
Container(width: 100.w, height: 50.h);
Text('hi', style: TextStyle(fontSize: 14.sp));

十六、常见坑 ​

1. 没在 MaterialApp 配 supportedLocales ​

→ AppLocalizations.of(context) 永远返回 null。 必须配 supportedLocales 和 localizationsDelegates。

2. 改完 ARB 没重启 ​

→ 看不到新 key。Flutter 重新生成代码需要重启(不是 hot reload)。

3. 字符串硬编码到处都是 ​

→ 后期国际化痛苦。从一开始所有 UI 文案过 l10n,即使只有一种语言。

4. 主题切换重建整个 App ​

→ 性能问题。其实 Flutter 的 InheritedWidget 机制只重建用了 Theme 的 Widget,大部分场景没问题。深层用 RepaintBoundary 隔离。

5. 动态字体配色失效 ​

dart
// ❌ 静态写死,主题变了不会更新
final color = Colors.blue;

// ✅
final color = Theme.of(context).colorScheme.primary;

十七、推荐组合 ​

i18n  → 官方 l10n + ARB(默认)
        / 已有大量翻译文件 → easy_localization
        / 强类型迷 → slang
主题  → Material 3 + ColorScheme.fromSeed
        + ThemeExtension 加品牌色
        + 文字 / 按钮 / 输入框统一定义
适配  → flutter_screenutil(设计稿映射)
       + LayoutBuilder(平板 / 桌面)
       + Cupertino 部分(iOS 用户体验)

十八、和已学知识的串联 ​

  • Locale / ThemeMode 用 Riverpod StateProvider 存(09)
  • 持久化到 SharedPreferences(14)
  • 切主题不需要重启 App,因为 InheritedWidget 自动通知所有订阅者(02 / 04)
  • 主题切换的过渡动画由 Material 自带(15:lerp 实现平滑过渡)
  • ThemeExtension 的 lerp 让你的自定义颜色也跟着平滑过渡

十九、心智模型 ​

i18n:
  ARB 文件 → 代码生成 → AppLocalizations.of(context).key
  Locale 由 MaterialApp 决定 → InheritedWidget 自动订阅 → UI 自动重译

Theme:
  ThemeData → Theme.of(context) 取 → InheritedWidget 自动订阅
  ColorScheme.fromSeed:1 个种子色 → 全套调色板
  ThemeExtension:加自己的字段

核心原则:所有文本走 i18n,所有颜色 / 字号走 theme。从第一行代码开始坚持,后期省掉 90% 重构。