ARB 文件与 gen_l10n 本地化工作流
配置 flutter_localizations 和 gen_l10n 流水线,生成类型化翻译。
ARB 文件与 gen_l10n 本地化工作流 是 CoddyKit 上的免费 Flutter Mobile Development 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Flutter Mobile Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Flutter Mobile Development 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Step 1: Why gen_l10n + dependencies
Hard-coding strings like Text('Welcome') makes an app impossible to translate. Flutter's official solution is gen_l10n: you write translations in ARB (Application Resource Bundle, a JSON format) files, and the build tool generates a typed Dart class so typos become compile-time errors.
Two pieces are required in pubspec.yaml. The flutter_localizations SDK package supplies Material/Cupertino/Widgets translations, and the generate: true flag turns on the gen_l10n build step.
intlis pulled in because generated code uses it for plurals and dates.- After editing, run
flutter pub get.
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: any
flutter:
generate: trueStep 2: l10n.yaml config
Create an l10n.yaml file at the project root. It tells gen_l10n where your ARB files live and what to name the generated class.
arb-dir— folder holding the.arbfiles.template-arb-file— the source-of-truth locale that defines keys and metadata.output-localization-file— name of the generated Dart file.output-class— the class name you import in code.
# l10n.yaml
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
output-class: AppLocalizationsStep 3: The template ARB file
The template locale (here app_en.arb) defines every key. Each key maps to a translated value. Keys starting with @ are metadata: they describe the entry but produce no string.
@@localedeclares which locale this file is.@welcomecan carry adescriptionto help translators.
The filename pattern is app_<localeCode>.arb.
{
"@@locale": "en",
"welcome": "Welcome",
"@welcome": {
"description": "Greeting shown on the home screen"
},
"settings": "Settings"
}Step 4: A translated ARB file
For each additional language, add a sibling file with the same keys but translated values. Metadata (the @ keys) is only required in the template; translations may omit it.
- Here
app_tr.arbprovides Turkish strings. - Missing keys fall back to the template locale, so keep the template complete.
{
"@@locale": "tr",
"welcome": "Hoş geldiniz",
"settings": "Ayarlar"
}Step 5: Generate the code
Code generation runs automatically during flutter run or flutter build when generate: true is set. You can also force it with flutter gen-l10n.
- Output lands in
.dart_tool/flutter_gen/gen_l10n/by default. - The generated
AppLocalizationsclass exposes one getter per key. - Add the generated path to your IDE's import suggestions; do not commit generated files.
Step 6: Wire into MaterialApp
Register the generated delegates and supported locales on MaterialApp. AppLocalizations.localizationsDelegates bundles your delegate plus the Material/Widgets/Cupertino ones, and supportedLocales lists what you ship.
- Flutter picks the best match between the device locale and
supportedLocales. - If none match, the first entry in
supportedLocalesis used.
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: const HomeScreen(),
);
}
}Step 7: Read a string
Inside a widget you fetch the localized instance with AppLocalizations.of(context) and read a getter. The call is null only if the delegates are missing, so the common idiom uses !.
- Each key from the ARB becomes a strongly-typed getter.
- Rename a key in the ARB and every wrong usage fails to compile.
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return Scaffold(
appBar: AppBar(title: Text(l10n.settings)),
body: Center(child: Text(l10n.welcome)),
);
}
}Step 8: Placeholders
To inject values, declare placeholders in the template metadata. The value uses {name} syntax, and gen_l10n turns the getter into a method.
- Each placeholder needs a
type(e.g.String,int,DateTime). - The generated method signature follows the placeholder order.
{
"@@locale": "en",
"greeting": "Hello, {name}!",
"@greeting": {
"description": "Personalized greeting",
"placeholders": {
"name": { "type": "String" }
}
}
}Step 9: Call a placeholder method
Because greeting takes an argument, the generated member is a method, not a getter. You pass the value at the call site.
l10n.greeting('Ada')returns "Hello, Ada!".- Types are enforced: passing an
intwhere aStringis expected fails to compile.
Widget buildGreeting(BuildContext context, String userName) {
final l10n = AppLocalizations.of(context)!;
return Text(l10n.greeting(userName));
}Step 10: Plurals with ICU
ARB supports ICU message syntax for plurals. A {count, plural, ...} block selects the right wording per language. Declare the placeholder as num (or int).
=0,one, andotherare common categories.#is replaced by the formatted number.- Different locales have different plural rules — ICU handles them automatically.
{
"itemCount": "{count, plural, =0{No items} one{1 item} other{{count} items}}",
"@itemCount": {
"placeholders": {
"count": { "type": "int" }
}
}
}Step 11: A plain-Dart formatter
The selection logic ICU performs is just rules over a number. Here is a tiny standalone Dart program that mimics English plural selection — useful for understanding what gen_l10n generates under the hood.
- Real apps use the generated method; this is only for intuition.
String itemCount(int count) {
if (count == 0) return 'No items';
if (count == 1) return '1 item';
return '$count items';
}
void main() {
for (final n in [0, 1, 5]) {
print(itemCount(n));
}
}Quick Check
You added a new key logout only to app_en.arb but forgot it in app_tr.arb. A Turkish-locale user opens the screen. What happens?
Recap
You built the full Flutter localization pipeline:
- Added
flutter_localizations+intland setgenerate: true. - Configured
l10n.yaml(arb-dir, template, output class). - Wrote a template ARB plus per-locale translations.
- Let gen_l10n create the typed
AppLocalizationsclass. - Registered
localizationsDelegatesandsupportedLocales, then read strings viaAppLocalizations.of(context)!. - Used placeholders for dynamic values and ICU plurals for count-aware text.
The payoff: translations are type-checked, missing template keys are caught early, and translators work in a clean JSON format.
常见问题解答
「ARB 文件与 gen_l10n 本地化工作流」课时是免费的吗?
是的 — 「ARB 文件与 gen_l10n 本地化工作流」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Flutter Mobile Development 课程的其余内容,请升级到 CoddyKit PRO。 Flutter Mobile Development 课程共包含 4 节课。
「ARB 文件与 gen_l10n 本地化工作流」这节课中我会学到什么?
配置 flutter_localizations 和 gen_l10n 流水线,生成类型化翻译。 你通过在浏览器中直接运行的动手代码来练习 Flutter Mobile Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Flutter Mobile Development 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Flutter Mobile Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「ARB 文件与 gen_l10n 本地化工作流」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Flutter Mobile Development 课中编写并运行代码吗?
能。每节 Flutter Mobile Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- ARB 文件与 gen_l10n 本地化工作流
- 复数、性别与 ICU 消息格式化
- RTL 布局与方向处理
- 语义、屏幕阅读器与无障碍组件