Sub topic 1
Internationalization versus localization in Flutter
Prerequisites
This chapter assumes you know basic Dart syntax and null safety. You should be able to build a simple Flutter app with StatelessWidget and MaterialApp, edit pubspec.yaml, and run flutter pub get.
Internationalization versus localization
Internationalization (often written i18n) is the work of preparing an app for many languages and regions. You move every user-facing string out of widget code and into translation files. Localization (l10n) is the work of adding one specific language or region. You do internationalization once, then localize for each language you support.
Flutter's gen-l10n tool reads your translation files and generates a Dart class that your widgets call to get text.
Adding flutter_localizations and intl
Add two packages to pubspec.yaml. The flutter_localizations package supplies translations for Material and Cupertino widgets, such as date pickers. The intl package provides date, number, and plural formatting.
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: any
flutter:
generate: trueintl: any lets pub pick the version that flutter_localizations requires. generate: true tells the build to run gen-l10n. Run flutter pub get after editing the file.
Configuring gen-l10n with l10n.yaml
Create l10n.yaml in the project root. It sets the folder of translation files, the template file, and the output file name.
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
synthetic-package: false> Note: the template file holds the source messages. Other languages are checked against it.
Setting synthetic-package: false writes the generated file next to your ARB files, so you can import it directly.
Writing ARB files
ARB (Application Resource Bundle) is a JSON-based format. Each message is a key with a text value. A key that starts with @ holds metadata, such as a description for translators.
{
"@@locale": "en",
"appTitle": "Trip Planner",
"@appTitle": {
"description": "Title shown in the app bar and task switcher"
}
}Save this file as lib/l10n/app_en.arb. A translated file, such as app_es.arb, repeats the keys with translated text and sets its own @@locale. It does not need the metadata, because gen-l10n reads that from the template.
Exercise
Why does the template ARB file need @ metadata entries while a translated ARB file does not?
Show answer
gen-l10n reads descriptions and placeholder types from the template to generate typed methods. Translated files only supply the text for each key, so the metadata is written once.