Sub topic 2
Generating the AppLocalizations class
This chapter assumes you have a Flutter project with flutter_localizations and intl in pubspec.yaml, generate: true set under flutter:, and a working MaterialApp. The chapter covers how the generated AppLocalizations class is created, wired in, and used, including placeholders.
Generating the AppLocalizations class
The gen-l10n tool reads a template ARB file and writes a Dart class. Create l10n.yaml at the project root:
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dartCreate lib/l10n/app_en.arb:
{
"@@locale": "en",
"appTitle": "Trip Planner",
"greeting": "Hello, {name}!",
"@greeting": {
"placeholders": {
"name": { "type": "String" }
}
}
}Run flutter pub get or flutter run. Each key becomes a getter or method on AppLocalizations. Placeholders become typed method parameters.
Connecting localizations to MaterialApp
Pass the generated delegates and locales to MaterialApp:
import 'package:flutter/material.dart';
import 'l10n/app_localizations.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
onGenerateTitle: (context) => AppLocalizations.of(context)!.appTitle,
home: const TripScreen(),
);
}
}| Property | Purpose |
|---|---|
| localizationsDelegates | Loads the app messages and the Material and Cupertino strings |
| supportedLocales | Lists the locales the app can show |
| onGenerateTitle | Sets a translated title for the task switcher |
:::note
Use AppLocalizations.of(context)! only below MaterialApp. Widgets above it have no localization in scope and get null.
:::
Using translated strings in widgets
Read messages through AppLocalizations.of(context):
import 'package:flutter/material.dart';
import 'l10n/app_localizations.dart';
class TripScreen extends StatelessWidget {
const TripScreen({super.key});
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return Scaffold(
appBar: AppBar(title: Text(l10n.appTitle)),
body: Center(child: Text(l10n.greeting('Ada'))),
);
}
}Placeholders and typed parameters
A placeholder such as {name} becomes a named Dart parameter whose type comes from the ARB metadata. Passing a value of the wrong type fails at compile time, so a missing or mistyped argument does not reach users.
Exercise
If greeting declares name as a String placeholder, what happens when you write l10n.greeting(42)?
Show answer
The Dart analyzer reports a compile-time error because 42 is an int, not a String.