flutter-setup-localization

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Internationalizing Flutter Applications

Flutter应用国际化

Contents

目录

Core Concepts

核心概念

Flutter handles internationalization (i18n) and localization (l10n) via the
flutter_localizations
and
intl
packages. The standard approach uses App Resource Bundle (
.arb
) files to define localized strings, which are then compiled into a generated
AppLocalizations
class for type-safe access within the widget tree.
Flutter通过
flutter_localizations
intl
包处理国际化(i18n)与本地化(l10n)。标准方案使用App Resource Bundle(
.arb
)文件定义本地化字符串,随后这些字符串会被编译为生成的
AppLocalizations
类,以便在widget树中进行类型安全的访问。

Setup Workflow

设置流程

Copy and track this checklist when initializing internationalization in a Flutter project:
  • Task Progress
    • 1. Add dependencies to
      pubspec.yaml
      .
    • 2. Enable the
      generate
      flag.
    • 3. Create the
      l10n.yaml
      configuration file.
    • 4. Configure
      MaterialApp
      or
      CupertinoApp
      .
在Flutter项目中初始化国际化时,可参考并跟踪以下检查清单:
  • 任务进度
    • 1. 向
      pubspec.yaml
      添加依赖。
    • 2. 启用
      generate
      标志。
    • 3. 创建
      l10n.yaml
      配置文件。
    • 4. 配置
      MaterialApp
      CupertinoApp

1. Add Dependencies

1. 添加依赖

Add the required localization packages to the project. Execute the following commands in the terminal:
bash
flutter pub add flutter_localizations --sdk=flutter
flutter pub add intl:any
Verify your
pubspec.yaml
includes the following under
dependencies
:
yaml
dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  intl: any
向项目添加所需的本地化包。在终端中执行以下命令:
bash
flutter pub add flutter_localizations --sdk=flutter
flutter pub add intl:any
验证你的
pubspec.yaml
dependencies
下包含以下内容:
yaml
dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  intl: any

2. Enable Code Generation

2. 启用代码生成

Open
pubspec.yaml
and enable the
generate
flag within the
flutter
section to automate localization tasks:
yaml
flutter:
  generate: true
打开
pubspec.yaml
,在
flutter
部分启用
generate
标志以自动化本地化任务:
yaml
flutter:
  generate: true

3. Create Configuration File

3. 创建配置文件

Create a new file named
l10n.yaml
in the root directory of the Flutter project. Define the input directory, template file, and output file:
yaml
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
synthetic-package: true
在Flutter项目的根目录下创建一个名为
l10n.yaml
的新文件。定义输入目录、模板文件和输出文件:
yaml
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
synthetic-package: true

4. Configure the App Entry Point

4. 配置应用入口

Import the generated localizations and the
flutter_localizations
library in your
main.dart
. Inject the delegates and supported locales into your
MaterialApp
or
CupertinoApp
.
dart
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; // Adjust path if synthetic-package is false

// ... inside build method
return MaterialApp(
  localizationsDelegates: const [
    AppLocalizations.delegate,
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
  ],
  supportedLocales: const [
    Locale('en'), // English
    Locale('es'), // Spanish
  ],
  home: const MyHomePage(),
);
main.dart
中导入生成的本地化文件和
flutter_localizations
库。将委托和支持的区域设置注入到
MaterialApp
CupertinoApp
中。
dart
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(),
);

Implementation Workflow

实现流程

Follow this workflow when adding or modifying localized content.
添加或修改本地化内容时,请遵循以下流程。

1. Define ARB Files

1. 定义ARB文件

  • If creating NEW content: Add the base string to the template file (
    lib/l10n/app_en.arb
    ). Include a description for context.
  • If EDITING existing content: Locate the key in all supported
    .arb
    files and update the values.
json
{
  "helloWorld": "Hello World!",
  "@helloWorld": {
    "description": "The conventional newborn programmer greeting"
  }
}
Create corresponding files for other locales (e.g.,
app_es.arb
):
json
{
  "helloWorld": "¡Hola Mundo!"
}
  • 如果创建新内容: 将基础字符串添加到模板文件(
    lib/l10n/app_en.arb
    )中,并包含用于上下文说明的描述。
  • 如果编辑现有内容: 在所有支持的
    .arb
    文件中找到对应的键并更新值。
json
{
  "helloWorld": "Hello World!",
  "@helloWorld": {
    "description": "The conventional newborn programmer greeting"
  }
}
为其他区域设置创建对应的文件(例如
app_es.arb
):
json
{
  "helloWorld": "¡Hola Mundo!"
}

2. Generate Localization Classes

2. 生成本地化类

Run the following command to trigger code generation:
bash
flutter pub get
Feedback Loop: Run validator -> review terminal output for ARB syntax errors -> fix missing commas or mismatched placeholders -> re-run
flutter pub get
.
运行以下命令触发代码生成:
bash
flutter pub get
反馈循环: 运行验证器 -> 查看终端输出中的ARB语法错误 -> 修复缺失的逗号或不匹配的占位符 -> 重新运行
flutter pub get

3. Consume Localized Strings

3. 使用本地化字符串

Access the localized strings in your widget tree using
AppLocalizations.of(context)
. Ensure the widget calling this is a descendant of
MaterialApp
.
dart
Text(AppLocalizations.of(context)!.helloWorld)
在widget树中使用
AppLocalizations.of(context)
访问本地化字符串。确保调用此方法的widget是
MaterialApp
的子节点。
dart
Text(AppLocalizations.of(context)!.helloWorld)

Advanced Formatting

高级格式化

Use placeholders for dynamic data, plurals, and conditional selects.
使用占位符处理动态数据、复数和条件选择。

Placeholders

占位符

Define parameters within curly braces and specify their type in the metadata object.
json
"hello": "Hello {userName}",
"@hello": {
  "description": "A message with a single parameter",
  "placeholders": {
    "userName": {
      "type": "String",
      "example": "Bob"
    }
  }
}
在大括号内定义参数,并在元数据对象中指定其类型。
json
"hello": "Hello {userName}",
"@hello": {
  "description": "A message with a single parameter",
  "placeholders": {
    "userName": {
      "type": "String",
      "example": "Bob"
    }
  }
}

Plurals

复数

Use the
plural
syntax to handle quantity-based string variations. The
other
case is mandatory.
json
"nWombats": "{count, plural, =0{no wombats} =1{1 wombat} other{{count} wombats}}",
"@nWombats": {
  "description": "A plural message",
  "placeholders": {
    "count": {
      "type": "num",
      "format": "compact"
    }
  }
}
使用
plural
语法处理基于数量的字符串变体。
other
情况是必填项。
json
"nWombats": "{count, plural, =0{no wombats} =1{1 wombat} other{{count} wombats}}",
"@nWombats": {
  "description": "A plural message",
  "placeholders": {
    "count": {
      "type": "num",
      "format": "compact"
    }
  }
}

Selects

选择

Use the
select
syntax for conditional strings, such as gendered text.
json
"pronoun": "{gender, select, male{he} female{she} other{they}}",
"@pronoun": {
  "description": "A gendered message",
  "placeholders": {
    "gender": {
      "type": "String"
    }
  }
}
使用
select
语法处理条件字符串,例如性别相关文本。
json
"pronoun": "{gender, select, male{he} female{she} other{they}}",
"@pronoun": {
  "description": "A gendered message",
  "placeholders": {
    "gender": {
      "type": "String"
    }
  }
}

Examples

示例

Complete
l10n.yaml

完整的
l10n.yaml

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

Complete Widget Implementation

完整的Widget实现

dart
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,
  });

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

    return Column(
      children: [
        Text(l10n.hello(userName)),
        Text(l10n.nWombats(notificationCount)),
      ],
    );
  }
}
dart
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,
  });

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

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