main
md 210 lines 5.78 KB
Rendered Raw
1 ---
2 name: flutter-setup-localization
3 description: Add `flutter_localizations` and `intl` dependencies, enable "generate true" in `pubspec.yaml`, and create an `l10n.yaml` configuration file. Use when initializing localization support for a new Flutter project.
4 metadata:
5 model: models/gemini-3.1-pro-preview
6 last_modified: Tue, 21 Apr 2026 21:27:35 GMT
7 ---
8 # Internationalizing Flutter Applications
9
10 ## Contents
11 - [Core Concepts](#core-concepts)
12 - [Setup Workflow](#setup-workflow)
13 - [Implementation Workflow](#implementation-workflow)
14 - [Advanced Formatting](#advanced-formatting)
15 - [Examples](#examples)
16
17 ## Core Concepts
18 Flutter handles internationalization (i18n) and localization (l10n) via the `flutter_localizations` and `intl` packages. The standard approach uses App Resource Bundle (`.arb`) files to define localized strings, which are then compiled into a generated `AppLocalizations` class for type-safe access within the widget tree.
19
20 ## Setup Workflow
21
22 Copy and track this checklist when initializing internationalization in a Flutter project:
23
24 - [ ] **Task Progress**
25 - [ ] 1. Add dependencies to `pubspec.yaml`.
26 - [ ] 2. Enable the `generate` flag.
27 - [ ] 3. Create the `l10n.yaml` configuration file.
28 - [ ] 4. Configure `MaterialApp` or `CupertinoApp`.
29
30 ### 1. Add Dependencies
31 Add the required localization packages to the project. Execute the following commands in the terminal:
32 ```bash
33 flutter pub add flutter_localizations --sdk=flutter
34 flutter pub add intl:any
35 ```
36
37 Verify your `pubspec.yaml` includes the following under `dependencies`:
38 ```yaml
39 dependencies:
40 flutter:
41 sdk: flutter
42 flutter_localizations:
43 sdk: flutter
44 intl: any
45 ```
46
47 ### 2. Enable Code Generation
48 Open `pubspec.yaml` and enable the `generate` flag within the `flutter` section to automate localization tasks:
49 ```yaml
50 flutter:
51 generate: true
52 ```
53
54 ### 3. Create Configuration File
55 Create a new file named `l10n.yaml` in the root directory of the Flutter project. Define the input directory, template file, and output file:
56 ```yaml
57 arb-dir: lib/l10n
58 template-arb-file: app_en.arb
59 output-localization-file: app_localizations.dart
60 synthetic-package: true
61 ```
62
63 ### 4. Configure the App Entry Point
64 Import the generated localizations and the `flutter_localizations` library in your `main.dart`. Inject the delegates and supported locales into your `MaterialApp` or `CupertinoApp`.
65
66 ```dart
67 import 'package:flutter_localizations/flutter_localizations.dart';
68 import 'package:flutter_gen/gen_l10n/app_localizations.dart'; // Adjust path if synthetic-package is false
69
70 // ... inside build method
71 return MaterialApp(
72 localizationsDelegates: const [
73 AppLocalizations.delegate,
74 GlobalMaterialLocalizations.delegate,
75 GlobalWidgetsLocalizations.delegate,
76 GlobalCupertinoLocalizations.delegate,
77 ],
78 supportedLocales: const [
79 Locale('en'), // English
80 Locale('es'), // Spanish
81 ],
82 home: const MyHomePage(),
83 );
84 ```
85
86 ## Implementation Workflow
87
88 Follow this workflow when adding or modifying localized content.
89
90 ### 1. Define ARB Files
91 * **If creating NEW content:** Add the base string to the template file (`lib/l10n/app_en.arb`). Include a description for context.
92 * **If EDITING existing content:** Locate the key in all supported `.arb` files and update the values.
93
94 ```json
95 {
96 "helloWorld": "Hello World!",
97 "@helloWorld": {
98 "description": "The conventional newborn programmer greeting"
99 }
100 }
101 ```
102
103 Create corresponding files for other locales (e.g., `app_es.arb`):
104 ```json
105 {
106 "helloWorld": "¡Hola Mundo!"
107 }
108 ```
109
110 ### 2. Generate Localization Classes
111 Run the following command to trigger code generation:
112 ```bash
113 flutter pub get
114 ```
115 *Feedback Loop:* Run validator -> review terminal output for ARB syntax errors -> fix missing commas or mismatched placeholders -> re-run `flutter pub get`.
116
117 ### 3. Consume Localized Strings
118 Access the localized strings in your widget tree using `AppLocalizations.of(context)`. Ensure the widget calling this is a descendant of `MaterialApp`.
119
120 ```dart
121 Text(AppLocalizations.of(context)!.helloWorld)
122 ```
123
124 ## Advanced Formatting
125
126 Use placeholders for dynamic data, plurals, and conditional selects.
127
128 ### Placeholders
129 Define parameters within curly braces and specify their type in the metadata object.
130 ```json
131 "hello": "Hello {userName}",
132 "@hello": {
133 "description": "A message with a single parameter",
134 "placeholders": {
135 "userName": {
136 "type": "String",
137 "example": "Bob"
138 }
139 }
140 }
141 ```
142
143 ### Plurals
144 Use the `plural` syntax to handle quantity-based string variations. The `other` case is mandatory.
145 ```json
146 "nWombats": "{count, plural, =0{no wombats} =1{1 wombat} other{{count} wombats}}",
147 "@nWombats": {
148 "description": "A plural message",
149 "placeholders": {
150 "count": {
151 "type": "num",
152 "format": "compact"
153 }
154 }
155 }
156 ```
157
158 ### Selects
159 Use the `select` syntax for conditional strings, such as gendered text.
160 ```json
161 "pronoun": "{gender, select, male{he} female{she} other{they}}",
162 "@pronoun": {
163 "description": "A gendered message",
164 "placeholders": {
165 "gender": {
166 "type": "String"
167 }
168 }
169 }
170 ```
171
172 ## Examples
173
174 ### Complete `l10n.yaml`
175 ```yaml
176 arb-dir: lib/l10n
177 template-arb-file: app_en.arb
178 output-localization-file: app_localizations.dart
179 synthetic-package: true
180 use-escaping: true
181 ```
182
183 ### Complete Widget Implementation
184 ```dart
185 import 'package:flutter/material.dart';
186 import 'package:flutter_gen/gen_l10n/app_localizations.dart';
187
188 class GreetingWidget extends StatelessWidget {
189 final String userName;
190 final int notificationCount;
191
192 const GreetingWidget({
193 super.key,
194 required this.userName,
195 required this.notificationCount,
196 });
197
198 @override
199 Widget build(BuildContext context) {
200 final l10n = AppLocalizations.of(context)!;
201
202 return Column(
203 children: [
204 Text(l10n.hello(userName)),
205 Text(l10n.nWombats(notificationCount)),
206 ],
207 );
208 }
209 }
210 ```