Communitygithub.com

Flutter 应用国际化

为 Flutter 项目添加 `flutter_localizations` 和 `intl` 依赖,在 `pubspec.yaml` 中启用 `generate: true`,并创建 `l10n.yaml` 配置文件。适用于为新 Flutter 项目初始化本地化支持。

Flutter 应用国际化 是什么?

此技能(Skill)用于在 Flutter 项目中实现国际化(i18n)和本地化(l10n)。它通过添加 `flutter_localizations` 和 `intl` 包依赖、在 `pubspec.yaml` 中启用 `generate: true` 标志以及创建 `l10n.yaml` 配置文件来完成初始设置。该技能基于 App Resource Bundle(`.arb`)文件方案,这些文件会被编译成类型安全的 `AppLocalizations` 类,以便在 widget 树中访问本地化字符串。它支持占位符、复数和条件选择等高级格式化功能,并提供了完整的设置流程,包括如何配置 `MaterialApp`、生成本地化类以及在小部件中消费本地化字符串。此技能适用于任何 Flutter 项目,并且遵循标准的 Flutter 本地化最佳实践。

兼容平台~Claude Code~Codex CLI~Cursor✓Gemini CLI
npx skills add https://github.com/dbillion/hermes-skills-public/tree/HEAD/skills-external/flutter-setup-localization

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Flutter 应用国际化 是做什么的?

目录

核心概念

Flutter 通过 flutter_localizations 和 intl 包处理国际化(i18n)和本地化(l10n)。标准方法使用 App Resource Bundle(.arb)文件定义本地化字符串,这些文件随后被编译成生成的 AppLocalizations 类,以在 widget 树中实现类型安全的访问。

设置工作流

在 Flutter 项目中初始化国际化时,请复制并跟踪此清单:

  • 任务进度
    • 1. 向 pubspec.yaml 添加依赖。
    • 2. 启用 generate 标志。
    • 3. 创建 l10n.yaml 配置文件。
    • 4. 配置 MaterialApp 或 CupertinoApp。

1. 添加依赖

将所需的本地化包添加到项目中。在终端中执行以下命令:

flutter pub add flutter_localizations --sdk=flutter
flutter pub add intl:any

验证你的 pubspec.yaml 在 dependencies 下包含以下内容:

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

2. 启用代码生成

打开 pubspec.yaml,在 flutter 部分启用 generate 标志以自动化本地化任务:

flutter:
  generate: true

3. 创建配置文件

在 Flutter 项目的根目录中创建一个名为 l10n.yaml 的新文件。定义输入目录、模板文件和输出文件:

arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
synthetic-package: true

4. 配置应用入口点

在你的 main.dart 中导入生成的本地化类和 flutter_localizations 库。将委托和支持的区域设置注入到你的 MaterialApp 或 CupertinoApp 中。

import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; // 如果 synthetic-package 为 false,请调整路径

// ... 在 build 方法内部
return MaterialApp(
  localizationsDelegates: const [
    AppLocalizations.delegate,
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
  ],
  supportedLocales: const [
    Locale('en'), // 英语
    Locale('es'), // 西班牙语
  ],
  home: const MyHomePage(),
);

实现工作流

在添加或修改本地化内容时,请遵循以下工作流。

1. 定义 ARB 文件

  • 如果创建新内容: 将基本字符串添加到模板文件(lib/l10n/app_en.arb)中。包含描述以提供上下文。
  • 如果编辑现有内容: 在所有支持的 .arb 文件中找到键并更新值。
{
  "helloWorld": "Hello World!",
  "@helloWorld": {
    "description": "新程序员惯用的问候语"
  }
}

为其他区域设置创建相应的文件(例如 app_es.arb):

{
  "helloWorld": "¡Hola Mundo!"
}

2. 生成本地化类

运行以下命令以触发代码生成:

flutter pub get

反馈循环: 运行验证器 -> 检查终端输出中的 ARB 语法错误 -> 修复缺失的逗号或不匹配的占位符 -> 重新运行 flutter pub get。

3. 消费本地化字符串

使用 AppLocalizations.of(context) 在你的 widget 树中访问本地化字符串。确保调用此方法的 widget 是 MaterialApp 的后代。

Text(AppLocalizations.of(context)!.helloWorld)

高级格式化

使用占位符处理动态数据、复数和条件选择。

占位符

在花括号内定义参数,并在元数据对象中指定其类型。

"hello": "Hello {userName}",
"@hello": {
  "description": "包含单个参数的消息",
  "placeholders": {
    "userName": {
      "type": "String",
      "example": "Bob"
    }
  }
}

复数

使用 plural 语法处理基于数量的字符串变体。other 情况是必需的。

"nWombats": "{count, plural, =0{没有袋熊} =1{1 只袋熊} other{{count} 只袋熊}}",
"@nWombats": {
  "description": "复数消息",
  "placeholders": {
    "count": {
      "type": "num",
      "format": "compact"
    }
  }
}

选择

使用 select 语法处理条件字符串,例如区分性别的文本。

"pronoun": "{gender, select, male{他} female{她} other{他们}}",
"@pronoun": {
  "description": "性别相关消息",
  "placeholders": {
    "gender": {
      "type": "String"
    }
  }
}

示例

完整的 l10n.yaml

arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
synthetic-package: true
use-escaping: true

完整的 Widget 实现

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

class GreetingWidget extends StatelessWidget {
  final String userName;
  final int notificationCount;

  const GreetingWidget({
    super.key, 
    required this.userName, 
    required this.notificationCount,
  });

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;

    return Column(
      children: [
        Text(l10n.hello(userName)),
        Text(l10n.nWombats(notificationCount)),
      ],
    );
  }
}

Individual skills in this repo

This repo contains 6 individual skills — each has its own dedicated page.

dbillion/hermes-skills-public

Edit an existing image based on a text prompt.

dbillion/hermes-skills-public

Expert in video composition, editing, and format conversion. Use when the user wants to generate high-quality video, overlay images on video, concatenate clips, create GIFs, or sync audio to video using mcp-avtool-go and mcp-veo-go.

dbillion/hermes-skills-public

All animation knowledge for HyperFrames — atomic motion rules, multi-phase scene blueprints, scene transitions, broader motion-design techniques, AND the seven runtime adapters (GSAP default, plus Lottie, Three.js, Anime.js, CSS keyframes, Web Animations API, TypeGPU). Use for any motion or animation task: pick 2-4 rules and compose, or load a blueprint, or look up runtime-specific API (e.g. GSAP eases / Lottie player / Three.js mixer). Also covers auditing an existing composition's choreography (animation map) and 24 named text-animation effects. HyperFrames-native: single paused timeline, seek-safe, deterministic.

dbillion/hermes-skills-public

Use the HyperFrames CLI development loop: init, add, catalog, capture, lint, check, snapshot, compare, grade-compare, preview, play, present, beats, keyframes, single or batch render, publish, cloud, cloudrun, feedback, lambda, doctor, browser, info, upgrade, skills, compositions, docs, benchmark, telemetry, transcribe, auth, tts, and remove-background. Also use when diagnosing build or render failures. validate, inspect, and layout are deprecated aliases; use check. Covers local, HeyGen-hosted cloud, AWS Lambda, and Google Cloud Run rendering.

dbillion/hermes-skills-public

The HyperFrames composition contract — build one renderable project. Use for composition structure, the `data-*` timing attributes, `class="clip"`, tracks, sub-compositions, variables, framework-owned media playback, deterministic-render rules, and validation. Also covers Tailwind projects and the STORYBOARD.md / SCRIPT.md plan formats. Read before writing composition HTML.

dbillion/hermes-skills-public

Non-animation creative direction for HyperFrames videos. Use for design spec (frame.md / design.md) handling, palettes, typography, narration, beat planning, audio-reactive visuals, composition patterns, and brand / style decisions. For atomic motion patterns and scene blueprints, use `hyperframes-animation`.

相关技能