Flutter localization with ARB files and Localeo
Wire a Flutter app to a Localeo release using flutter_localizations, intl and the gen-l10n code generator. You’ll download Localeo’s ARB files before each build, generate a typed AppLocalizations class from them, and prove the result with a widget test.
- Framework
- Flutter 3.50 (also checked on 3.29), intl 0.20
- Format
- ARB
- Time
- 20 minutes
Find your ARB files
In Localeo, open your project and go to Releases. Every published release has a download link per language and format, and there is also a
latestlink that always points at the newest published release. You’ll use the ARB links:bash # a pinned release: never changes, cached for a yearhttps://cdn.localeo.app/p/<projectSlug>/r/<releaseSlug>/<lang>.arb # the newest published release: cached for about a minute, refreshed on publishhttps://cdn.localeo.app/p/<projectSlug>/r/latest/<lang>.arbFlutter turns every ARB message into a Dart getter, so Localeo writes each key as a valid Dart identifier:
checkout.pay_buttonbecomescheckoutPayButtonandcart.itemsbecomescartItems. A name that would start with a digit or is a Dart reserved word gets akprefix (404.title→k404Title), and two keys that derive the same name get2,3… appended. Every file carries@@localeand the@metadata, including placeholder types:nl.arb { "@@locale": "nl", "@appTitle": { "description": "The app name in the header" }, "@cartGreeting": { "description": "Greeting on the cart page", "placeholders": { "name": { "description": "Customer first name", "type": "String" } } }, "@cartItems": { "description": "Item count in the cart badge", "placeholders": { "count": { "type": "int" } } }, "@checkoutPayButton": { "description": "Pay button", "placeholders": { "amount": { "type": "String" } } }, "@errorsRetry": { "description": "Generic retry message" }, "appTitle": "Acme Winkel", "cartGreeting": "Hoi {name}, welkom terug!", "cartItems": "{count, plural, one {{count} artikel} other {{count} artikelen}}", "checkoutPayButton": "Nu {amount} betalen", "errorsRetry": "Er ging iets mis. Opnieuw proberen?"}A key with no translation in a language is left out of that language’s file, and a language with nothing translated yet gets a file with only
@@locale. A publish includes every value, drafts too.Set up gen-l10n
Add the two localization packages.
intlis pinned byflutter_localizations, so let it pick the version:bash flutter pub add flutter_localizations --sdk=flutterflutter pub add intl:anyThen turn on code generation in
pubspec.yaml. Thematerial_uidependency comes from the Flutter 3.50 project template:pubspec.yaml dependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter intl: any material_ui: ^1.1.0 flutter: generate: true uses-material-design: truePoint gen-l10n at the folder the ARB files will be downloaded into, with your base language as the template. The template decides which messages exist and what their placeholders are; every other language is checked against it:
l10n.yaml arb-dir: lib/l10ntemplate-arb-file: app_en.arboutput-localization-file: app_localizations.dartuntranslated-messages-file: untranslated.jsonnullable-getter: falseDownload the ARB files before gen-l10n
This script fetches one ARB file per language into
lib/l10n/. Run it in CI beforeflutter gen-l10n. It uses nothing but the Dart SDK that comes with Flutter, and stops the build if a download fails:tool/fetch_translations.dart // Downloads Localeo's ARB files into lib/l10n/ before `flutter gen-l10n`.// LOCALEO_CDN_URL e.g. https://cdn.localeo.app// LOCALEO_PROJECT your project's public slug// LOCALEO_RELEASE a release slug for a pinned build, or "latest" (default)// LOCALEO_LANGUAGES language codes as Localeo writes them, space-separatedimport 'dart:convert';import 'dart:io'; Future<void> main() async { final env = Platform.environment; final cdn = env['LOCALEO_CDN_URL'] ?? 'https://cdn.localeo.app'; final project = env['LOCALEO_PROJECT'] ?? (throw StateError('Set LOCALEO_PROJECT')); final release = env['LOCALEO_RELEASE'] ?? 'latest'; final languages = (env['LOCALEO_LANGUAGES'] ?? 'en nl pt-BR').split(' '); final client = HttpClient(); try { for (final lang in languages) { final uri = Uri.parse('$cdn/p/$project/r/$release/$lang.arb'); final response = await (await client.getUrl(uri)).close(); // Only the file name: the URL contains your project slug. if (response.statusCode != HttpStatus.ok) { throw HttpException('$lang.arb: HTTP ${response.statusCode}'); } final arb = jsonDecode(await response.transform(utf8.decoder).join()); // gen-l10n only accepts underscores: Localeo's "pt-BR" becomes "pt_BR". await writeArb(lang.replaceAll('-', '_'), arb); // gen-l10n refuses pt_BR without a plain pt file. If the project has no // plain "pt" language, reuse the regional file as the language fallback. final base = lang.split('-').first; if (base != lang && !languages.contains(base)) await writeArb(base, arb); } } finally { client.close(); }} /// Writes lib/l10n/app_[locale].arb with a matching "@@locale".Future<void> writeArb(String locale, Map<String, dynamic> arb) async { final file = File('lib/l10n/app_$locale.arb'); await file.create(recursive: true); await file.writeAsString(jsonEncode({...arb, '@@locale': locale})); stdout.writeln(file.path);}The script handles two things gen-l10n is strict about:
- Underscores, not hyphens. Localeo names regional languages the BCP 47 way (
pt-BR), but gen-l10n rejects"@@locale": "pt-BR"as “not a supported language code”, and complains when@@localeand the file name disagree. The script rewrites both topt_BR. - A plain language for every regional one. gen-l10n refuses to generate
pt_BRwithout aptfile next to it. If your project has no plain Portuguese, the script copies the Brazilian file asapp_pt.arb, so devices set to Portuguese from Portugal get Brazilian text rather than your base language. Add a realptlanguage in Localeo if you’d rather control that.
The
app_prefix is a convention, not a requirement: with@@localein the file, gen-l10n acceptsnl.arbtoo. What it does require is that a locale in the file name, if there is one, matches@@locale. In CI, the whole sequence looks like this:bash export LOCALEO_CDN_URL=https://cdn.localeo.appexport LOCALEO_PROJECT=<projectSlug> # store it as a CI secretexport LOCALEO_RELEASE=<releaseSlug> # or leave unset for "latest"export LOCALEO_LANGUAGES="en nl pt-BR" dart run tool/fetch_translations.dartflutter gen-l10nflutter analyzeflutter testflutter build web # or apk, appbundle, ipa…- Underscores, not hyphens. Localeo names regional languages the BCP 47 way (
Use AppLocalizations in your widgets
gen-l10n writes
lib/l10n/app_localizations.dartwith one member per message: a getter for plain text (appTitle) and a method for messages with placeholders (cartGreeting(String name),cartItems(int count)). The placeholder types come from the template file, so a parameter you typed asintin Localeo is anintin Dart:lib/main.dart import 'package:material_ui/material_ui.dart'; import 'l10n/app_localizations.dart'; void main() => runApp(const ShopApp()); class ShopApp extends StatelessWidget { const ShopApp({super.key, this.locale}); /// Forces a locale (handy in tests); null means "follow the device". final Locale? locale; @override Widget build(BuildContext context) { return MaterialApp( locale: locale, onGenerateTitle: (context) => AppLocalizations.of(context).appTitle, localizationsDelegates: const [ AppLocalizations.delegate, // Not AppLocalizations.localizationsDelegates: on Flutter 3.47+ that // list still holds flutter_localizations' Material delegates, which // material_ui's MaterialApp does not recognise. ...GlobalMaterialLocalizations.delegates, ], supportedLocales: AppLocalizations.supportedLocales, home: const CartPage(), ); }} class CartPage extends StatelessWidget { const CartPage({super.key}); @override Widget build(BuildContext context) { final t = AppLocalizations.of(context); return Scaffold( appBar: AppBar(title: Text(t.appTitle)), body: Column( children: [ Text(t.cartGreeting('Sam')), Text(t.cartItems(1)), Text(t.cartItems(5)), FilledButton( onPressed: () {}, child: Text(t.checkoutPayButton('€ 12,50')), ), ], ), ); }}The same generated file trips
flutter analyzeon Flutter 3.47 and newer: it still uses those deprecated delegates, so the analyzer reports two infos and exits with an error. It is generated code, so add it to the exclude list the project template already has:analysis_options.yaml analyzer: exclude: - lib/l10n/app_localizations*.dartWrite values gen-l10n can compile, and test them
Localeo passes your values through byte for byte, so they have to be written the way gen-l10n reads them. Three things to watch for in the base language especially:
- Plurals use the placeholder, not
#. gen-l10n does not replace#with the number:{count, plural, one {# item} other {# items}}renders a literal “# items”. Write{count, plural, one {{count} item} other {{count} items}}instead. - Type dates as
String. ADateTimeplaceholder stops gen-l10n with an error unless it has aformatattribute, and Localeo’s ARB files don’t carry one. Declare the parameter asStringand format the date in Dart before passing it in, for example withDateFormat.yMMMd(t.localeName).format(date)fromintl. - Translate the base language first. The template defines which messages exist. A key with no base-language value is missing from the template, and gen-l10n drops it silently from every language: there is no getter for it at all.
A key that is translated in the base language but not in another one falls back to the base language: gen-l10n copies the template’s text into that language’s generated class and lists the key in
untranslated.json. In the demo project,checkout.pay_buttonhas no Brazilian Portuguese translation:untranslated.json { "pt": [ "checkoutPayButton" ], "pt_BR": [ "checkoutPayButton" ]}A widget test proves the whole chain, from downloaded ARB file to rendered text, including the interpolation, both plural forms and the fallback:
test/localization_test.dart import 'package:material_ui/material_ui.dart';import 'package:flutter_test/flutter_test.dart';import 'package:shop/main.dart'; // your app's package name void main() { testWidgets('renders Dutch from the Localeo ARB file', (tester) async { await tester.pumpWidget(const ShopApp(locale: Locale('nl'))); await tester.pumpAndSettle(); expect(find.text('Acme Winkel'), findsOneWidget); expect(find.text('Hoi Sam, welkom terug!'), findsOneWidget); expect(find.text('1 artikel'), findsOneWidget); expect(find.text('5 artikelen'), findsOneWidget); expect(find.text('Nu € 12,50 betalen'), findsOneWidget); }); testWidgets('pt-BR falls back to the base language', (tester) async { await tester.pumpWidget(const ShopApp(locale: Locale('pt', 'BR'))); await tester.pumpAndSettle(); expect(find.text('Olá Sam, bem-vindo de volta!'), findsOneWidget); expect(find.text('5 itens'), findsOneWidget); // checkout.pay_button is not translated into pt-BR, so English is used. expect(find.text('Pay € 12,50 now'), findsOneWidget); });}- Plurals use the placeholder, not
Choose a pinned release or latest
gen-l10n compiles your translations into Dart code, so they ship inside the app binary. There is no runtime download: a copy change reaches your users only through a new build and, on mobile, a new store release. Localeo has no SDK for over-the-air updates, so which link you download decides how reproducible your builds are:
- A pinned release (
LOCALEO_RELEASEset to a release slug) never changes, so rebuilding a tag produces the same strings. Use it for store builds, and bump the slug as a deliberate change. latestpicks up whatever was published most recently, within about a minute. It suits nightly or preview builds that should always carry current copy, at the cost of two builds of the same commit possibly differing.
- A pinned release (
Next steps
- Releases and bundles: how ARB message names are derived, file formats and caching.
- Webhooks: the
release_publishedevent and how to verify its signature.
Ship it with Localeo
Create a project, add your languages and publish your first release. Then point this setup at its links.
Get started