flutter-setup-localization
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseInternationalizing Flutter Applications
Flutter应用国际化
Contents
目录
Core Concepts
核心概念
Flutter handles internationalization (i18n) and localization (l10n) via the and packages. The standard approach uses App Resource Bundle () files to define localized strings, which are then compiled into a generated class for type-safe access within the widget tree.
flutter_localizationsintl.arbAppLocalizationsFlutter通过和包处理国际化(i18n)与本地化(l10n)。标准方案使用App Resource Bundle()文件定义本地化字符串,随后这些字符串会被编译为生成的类,以便在widget树中进行类型安全的访问。
flutter_localizationsintl.arbAppLocalizationsSetup Workflow
设置流程
Copy and track this checklist when initializing internationalization in a Flutter project:
- Task Progress
- 1. Add dependencies to .
pubspec.yaml - 2. Enable the flag.
generate - 3. Create the configuration file.
l10n.yaml - 4. Configure or
MaterialApp.CupertinoApp
- 1. Add dependencies to
在Flutter项目中初始化国际化时,可参考并跟踪以下检查清单:
- 任务进度
- 1. 向添加依赖。
pubspec.yaml - 2. 启用标志。
generate - 3. 创建配置文件。
l10n.yaml - 4. 配置或
MaterialApp。CupertinoApp
- 1. 向
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:anyVerify your includes the following under :
pubspec.yamldependenciesyaml
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: any向项目添加所需的本地化包。在终端中执行以下命令:
bash
flutter pub add flutter_localizations --sdk=flutter
flutter pub add intl:any验证你的在下包含以下内容:
pubspec.yamldependenciesyaml
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: any2. Enable Code Generation
2. 启用代码生成
Open and enable the flag within the section to automate localization tasks:
pubspec.yamlgenerateflutteryaml
flutter:
generate: true打开,在部分启用标志以自动化本地化任务:
pubspec.yamlfluttergenerateyaml
flutter:
generate: true3. Create Configuration File
3. 创建配置文件
Create a new file named in the root directory of the Flutter project. Define the input directory, template file, and output file:
l10n.yamlyaml
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
synthetic-package: true在Flutter项目的根目录下创建一个名为的新文件。定义输入目录、模板文件和输出文件:
l10n.yamlyaml
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
synthetic-package: true4. Configure the App Entry Point
4. 配置应用入口
Import the generated localizations and the library in your . Inject the delegates and supported locales into your or .
flutter_localizationsmain.dartMaterialAppCupertinoAppdart
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.dartflutter_localizationsMaterialAppCupertinoAppdart
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 (). Include a description for context.
lib/l10n/app_en.arb - If EDITING existing content: Locate the key in all supported files and update the values.
.arb
json
{
"helloWorld": "Hello World!",
"@helloWorld": {
"description": "The conventional newborn programmer greeting"
}
}Create corresponding files for other locales (e.g., ):
app_es.arbjson
{
"helloWorld": "¡Hola Mundo!"
}- 如果创建新内容: 将基础字符串添加到模板文件()中,并包含用于上下文说明的描述。
lib/l10n/app_en.arb - 如果编辑现有内容: 在所有支持的文件中找到对应的键并更新值。
.arb
json
{
"helloWorld": "Hello World!",
"@helloWorld": {
"description": "The conventional newborn programmer greeting"
}
}为其他区域设置创建对应的文件(例如):
app_es.arbjson
{
"helloWorld": "¡Hola Mundo!"
}2. Generate Localization Classes
2. 生成本地化类
Run the following command to trigger code generation:
bash
flutter pub getFeedback 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 get3. Consume Localized Strings
3. 使用本地化字符串
Access the localized strings in your widget tree using . Ensure the widget calling this is a descendant of .
AppLocalizations.of(context)MaterialAppdart
Text(AppLocalizations.of(context)!.helloWorld)在widget树中使用访问本地化字符串。确保调用此方法的widget是的子节点。
AppLocalizations.of(context)MaterialAppdart
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 syntax to handle quantity-based string variations. The case is mandatory.
pluralotherjson
"nWombats": "{count, plural, =0{no wombats} =1{1 wombat} other{{count} wombats}}",
"@nWombats": {
"description": "A plural message",
"placeholders": {
"count": {
"type": "num",
"format": "compact"
}
}
}使用语法处理基于数量的字符串变体。情况是必填项。
pluralotherjson
"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 syntax for conditional strings, such as gendered text.
selectjson
"pronoun": "{gender, select, male{he} female{she} other{they}}",
"@pronoun": {
"description": "A gendered message",
"placeholders": {
"gender": {
"type": "String"
}
}
}使用语法处理条件字符串,例如性别相关文本。
selectjson
"pronoun": "{gender, select, male{he} female{she} other{they}}",
"@pronoun": {
"description": "A gendered message",
"placeholders": {
"gender": {
"type": "String"
}
}
}Examples
示例
Complete l10n.yaml
l10n.yaml完整的l10n.yaml
l10n.yamlyaml
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
synthetic-package: true
use-escaping: trueyaml
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
synthetic-package: true
use-escaping: trueComplete 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)),
],
);
}
}