Sub topic 5
Generating the AppLocalizations class
This chapter assumes you can edit pubspec.yaml, you have already added flutter_localizations and intl, and you have an l10n.yaml and a template ARB file such as lib/l10n/app_en.arb. Here you will see what the gen-l10n tool does with those inputs, how to run it, what it writes, and how to fix the errors you are most likely to meet.
What gen-l10n produces
gen-l10n is a code generator that ships with the Flutter SDK. It reads every ARB file in the directory named by arb-dir. It uses the file named by template-arb-file as the source of truth for message keys, descriptions, and placeholder types. It then writes Dart code that your app imports like any other library.
With the configuration from the previous chapters, the output goes into lib/l10n/:
lib/l10n/
app_en.arb
app_es.arb
app_localizations.dart (generated)
app_localizations_en.dart (generated)
app_localizations_es.dart (generated)The files fit together like this:
app_localizations.dartdeclares the abstract classAppLocalizations. It has one abstract member per message, a staticof(context)lookup, the delegate, and the listslocalizationsDelegatesandsupportedLocales.app_localizations_en.dartandapp_localizations_es.darteach contain a subclass with the real strings for one language, such asAppLocalizationsEn.- The
lookupAppLocalizations(Locale)function at the bottom of the main file picks the subclass for a locale.
Your widgets only use the abstract type. They never import the per-language files.
When generation runs
There are two ways to trigger generation.
- Automatically. With
generate: trueunderflutter:inpubspec.yaml, bothflutter pub getandflutter runregenerate the code. Most IDEs runflutter pub getwhen you savepubspec.yaml, but they do not run it when you edit an ARB file. During a debug session, restart the app after an ARB edit so thatflutter rungenerates again. - Manually. Run the tool directly:
flutter gen-l10nRunning it by hand is the quickest way to check an ARB edit. It prints errors from the tool itself, and you do not have to wait for a full build. It is also the right step in continuous integration, before flutter analyze, because generated files that are not committed will not exist on a fresh checkout.
Where the output goes
The synthetic-package setting in l10n.yaml decides where the generated files land.
| Setting | Output location | Import in your code |
|---|---|---|
| `synthetic-package: false` | Next to the ARB files, in `arb-dir` (or in `output-dir` if you set it) | A relative or `package:your_app/l10n/app_localizations.dart` import |
| `synthetic-package: true` (older default) | A hidden package under `.dart_tool/flutter_gen` | `package:flutter_gen/gen_l10n/app_localizations.dart` |
This tutorial uses false, so the files sit in your source tree where you can open them and the analyzer sees them. Newer Flutter releases are phasing out the synthetic package, so choosing false now avoids a later migration. Check the release notes for your Flutter version if your project still uses the old import.
Because the files are ordinary source files, you decide whether to commit them. Teams that commit them get a working checkout without any setup. Teams that ignore them must run flutter gen-l10n or flutter pub get before analysis and tests. Pick one rule and apply it to the whole repository, because a half-committed set of generated files produces confusing diffs.
What the generated API looks like
Each key in the template ARB becomes a member of AppLocalizations. For the Trip Planner template from the previous chapter, the generated members are:
| ARB key | Generated member | Why |
|---|---|---|
| `appTitle` | `String get appTitle` | No placeholders, so it is a getter. |
| `greeting` | `String greeting(String name)` | One `String` placeholder. |
| `tripCount` | `String tripCount(int count)` | The plural placeholder is typed `int`. |
| `departure` | `String departure(DateTime date)` | `DateTime` type with a `format` of `yMMMd`. |
A message with no placeholders is a getter. A message with placeholders is a method, and each placeholder becomes a parameter in the order it first appears in the message text. If a placeholder has no type, its parameter is typed Object, so declare types in the metadata whenever you can. That is what lets the compiler reject l10n.tripCount('three').
Getting an instance uses the lookup you wired into MaterialApp:
final l10n = AppLocalizations.of(context)!;By default of returns a nullable value, which is why the ! appears. If you set nullable-getter: false in l10n.yaml, of returns a non-null AppLocalizations and you can drop the !. That is safe only when every route that calls it sits below a MaterialApp configured with the delegates.
How the generated delegate works
AppLocalizations.delegate is a LocalizationsDelegate<AppLocalizations>. When the Localizations widget under MaterialApp learns the active locale, it asks the delegate to load. The generated load method calls lookupAppLocalizations(locale), which switches on locale.languageCode and returns the matching subclass. The result is wrapped in a SynchronousFuture, so the strings are available in the same frame and no loading screen is needed.
The supportedLocales list is built from the @@locale value, or the file-name suffix, of each ARB file in the directory. Adding app_fr.arb and regenerating adds Locale('fr') to that list. You do not edit any Dart code to add a language.
localizationsDelegates contains the generated delegate plus GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, and GlobalCupertinoLocalizations.delegate. These supply the translated strings of the framework widgets, such as the date picker buttons and the text direction.
Useful l10n.yaml options for generation
These optional keys change what the generator writes. Add them only when you need them.
output-dir: write the generated files to a directory other thanarb-dir.output-class: use a class name other thanAppLocalizations.nullable-getter: set tofalsefor a non-nullof.header: text placed at the top of each generated file, such as a license notice.use-escaping: lets you wrap literal text in single quotes in an ARB message so that braces are not read as placeholders.required-resource-attributes: set totrueto make the tool fail when a message has no@keymetadata entry.
The tool also accepts a few of these as command-line flags, but keeping everything in l10n.yaml gives you one place to read the configuration.
Common errors and how to read them
Most generation failures come from ARB content or configuration. The tool stops at the first failure and names the file and message.
- The template file is missing.
template-arb-filemust name a file that exists insidearb-dir. A typo here fails immediately. - A placeholder is used but not declared. If a message contains
{name}but the metadata has nonameentry, the tool reports that the placeholder is not defined. Declare it underplaceholdersin the template file. - A placeholder is declared but not used. This is also an error or a warning, depending on the context. Delete the unused metadata.
- A bad ICU message. A plural without an
othercase, or unbalanced braces, produces an ICU parsing error that points at the message key. - A translation uses a different placeholder. Translated files must use the same placeholder names as the template. A translator who changes
{name}to{nombre}breaks the build. - Imports still point at the old location. If you changed
synthetic-package, the analyzer reports thatpackage:flutter_gen/gen_l10n/app_localizations.dartdoes not exist. Change the import to the new file path. - Stale output. If you edit an ARB file and the app still shows the old text, run
flutter gen-l10n, then do a full restart instead of a hot reload.
A quick check for a suspected stale result is to open app_localizations.dart and search for the key. If the member is not there, generation did not run or failed.
Exercises
Exercise
You add a message "farewell": "Goodbye, {name}!" to app_en.arb with no @farewell metadata, then run flutter gen-l10n. What type does the name parameter of farewell have, and how do you make the generator reject a call like l10n.farewell(42)?
Show answer
Without a declared type, the placeholder becomes an Object parameter, so the call compiles. Add an @farewell entry with "placeholders": {"name": {"type": "String"}} and regenerate. The method becomes String farewell(String name), and passing 42 is then a compile-time error.
Exercise
Your teammate pulls the repository, runs the tests, and gets "Target of URI doesn't exist: 'l10n/app_localizations.dart'". Your l10n.yaml has synthetic-package: false and the generated files are not committed. Give two ways to fix this.
Show answer
Run flutter gen-l10n (or flutter pub get with generate: true set) before analyzing or testing, and add that step to the setup instructions and CI. Alternatively, commit the generated files in lib/l10n/ so a fresh checkout already contains them.