Mobile Development
FlutterInternationalizationLocalizationCI/CDMobile Development

Flutter i18n/L10n Guide: Plurals, RTL, Locale Fallbacks, and CI Checks

AO
Adrijan Omićević
·12 min read

# What You’ll Build in This Flutter Internationalization Guide#

This guide shows a production-ready localization setup for Flutter using ARB files, Flutter gen-l10n, and ICU message syntax. You’ll implement plurals and gender, right-to-left layouts, locale fallback behavior, and date and number formatting.

You’ll also add CI checks that fail builds when ARB files are invalid, keys are missing, or generated localization code is out of sync. This matters because localization defects are high-impact and easy to miss in code review, especially when changes ship frequently.

# Prerequisites#

RequirementVersionNotes
Flutter3.22 or newergen-l10n is stable and widely supported
DartComes with FlutterKeep SDK pinned via FVM or CI
intl0.19 or newerFor date and number formatting
GitHub ActionsAnyExample CI workflow uses Ubuntu runner

ℹ️ Note: If you already run a robust pipeline, integrate the checks from this guide into your existing job graph. For a broader pipeline overview, see Flutter CI/CD: GitHub Actions, Codemagic, Fastlane.

# Step 1: Enable Flutter localization and generate AppLocalizations#

Flutter’s built-in localization workflow uses ARB files and generates a strongly typed localization API. This avoids fragile string-based lookups and makes missing keys obvious during compilation.

1) Add dependencies#

Add the localization SDK and intl:

YAML
# pubspec.yaml
dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  intl: ^0.19.0

Run:

Bash
flutter pub get

2) Configure gen-l10n#

Add a l10n config file:

YAML
# l10n.yaml
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
output-class: AppLocalizations
synthetic-package: false
nullable-getter: false

Create the directory and your first ARB file:

JSON
// lib/l10n/app_en.arb
{
  "@@locale": "en",
  "appTitle": "Acme Wallet",
  "@appTitle": {
    "description": "App name shown in the system app switcher"
  }
}

Generate localizations:

Bash
flutter gen-l10n

3) Wire localization into MaterialApp#

Update your app entry:

Dart
// lib/main.dart
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.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(
      onGenerateTitle: (context) => AppLocalizations.of(context)!.appTitle,
      localizationsDelegates: const [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: AppLocalizations.supportedLocales,
      home: const Scaffold(body: Center(child: HomeTitle())),
    );
  }
}
 
class HomeTitle extends StatelessWidget {
  const HomeTitle({super.key});
 
  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    return Text(l10n.appTitle);
  }
}

Why this matters: you get compile-time method names for your strings, and Flutter automatically picks the correct locale from the device settings when it’s supported.

💡 Tip: Commit the generated localization file to your repo when your team benefits from easier diffs and consistent builds. Then enforce it in CI by failing when generation changes tracked files.

# Step 2: Add locale fallbacks that behave predictably#

Locale fallback issues cause the most visible production bugs: users see blank labels, incorrect languages, or partial translations. Flutter’s resolution can be controlled, and you should define how to handle region variants.

Support language-only locales and a small set of region-specific locales when needed:

LocaleUse whenExample
enDefault for EnglishMost apps
en_GBRegional spelling and date formatsUK market
ptBrazilian and European Portuguese share enough textEarly-stage
pt_BR and pt_PTTerminology differs materiallyFintech, legal-heavy apps

Add a locale resolution callback#

This gives you explicit fallback rules, for example falling back from en_AU to en:

Dart
// inside MaterialApp
localeResolutionCallback: (deviceLocale, supportedLocales) {
  if (deviceLocale == null) return const Locale('en');
 
  for (final locale in supportedLocales) {
    final sameLanguage = locale.languageCode == deviceLocale.languageCode;
    final sameCountry = locale.countryCode == deviceLocale.countryCode;
 
    if (sameLanguage && (locale.countryCode == null || sameCountry)) {
      return locale;
    }
  }
 
  for (final locale in supportedLocales) {
    if (locale.languageCode == deviceLocale.languageCode) return locale;
  }
 
  return const Locale('en');
},

Why this matters: language-only fallback avoids shipping dozens of region ARB files early, while still respecting user expectations in most cases.

⚠️ Warning: Avoid forcing a locale globally during development and forgetting to remove it. A hard-coded locale can ship to production and make your app ignore user settings.

# Step 3: ICU plurals and gender, correctly#

Plural rules vary significantly by language. English has two forms, while Arabic has six, and Slavic languages have multiple forms based on the count. Relying on manual if count == 1 logic breaks quickly.

Flutter’s ARB messages support ICU syntax. The generator turns these into typed Dart methods.

Plurals with ICU#

Add a plural message:

JSON
// lib/l10n/app_en.arb
{
  "@@locale": "en",
  "itemsInCart": "{count, plural, =0{No items} =1{1 item} other{{count} items}}",
  "@itemsInCart": {
    "description": "Label showing number of items in the cart",
    "placeholders": {
      "count": { "type": "int" }
    }
  }
}

Croatian example with multiple plural forms:

JSON
// lib/l10n/app_hr.arb
{
  "@@locale": "hr",
  "itemsInCart": "{count, plural, =0{Nema stavki} one{{count} stavka} few{{count} stavke} other{{count} stavki}}",
  "@itemsInCart": {
    "description": "Broj stavki u košarici",
    "placeholders": {
      "count": { "type": "int" }
    }
  }
}

Use it in code:

Dart
final l10n = AppLocalizations.of(context)!;
Text(l10n.itemsInCart(cartCount));

Why this matters: ICU plural categories such as one, few, and other are language-specific. You let the localization system decide the correct form.

Gender or other selection logic#

A pragmatic approach is select with a string selector. Keep it simple and consistent across languages.

JSON
// lib/l10n/app_en.arb
{
  "invitedUser": "{gender, select, male{He invited you} female{She invited you} other{They invited you}}",
  "@invitedUser": {
    "placeholders": {
      "gender": { "type": "String" }
    }
  }
}

Call it:

Dart
Text(l10n.invitedUser(userGender)); // "male", "female", or "other"

🎯 Key Takeaway: Plurals and gender are translation problems, not UI logic problems. Keep branching out of widgets and inside ICU messages.

# Step 4: Right-to-left support without layout regressions#

RTL is not only about text direction. It impacts alignment, padding, icons, animations, and sometimes navigation transitions. If you don’t test RTL explicitly, you will ship clipped headers and misaligned buttons.

Use direction-aware spacing#

Prefer direction-aware APIs:

What you needUse thisAvoid this
Horizontal paddingEdgeInsetsDirectional.only(start: 16, end: 16)EdgeInsets.only(left: 16, right: 16)
AlignmentAlignmentDirectional.centerStartAlignment.centerLeft
Positioned offsetsPositionedDirectional(start: 0)Positioned(left: 0)
Row orderingRow(textDirection: ...) only when necessaryManual reversing lists everywhere

Example:

Dart
Padding(
  padding: const EdgeInsetsDirectional.only(start: 16, end: 16),
  child: Align(
    alignment: AlignmentDirectional.centerStart,
    child: Text(l10n.appTitle),
  ),
)

Add an RTL locale and test it#

Add Arabic or Hebrew ARB, even if initially minimal:

JSON
// lib/l10n/app_ar.arb
{
  "@@locale": "ar",
  "appTitle": "محفظة أكمي"
}

Run flutter gen-l10n and your app can now render in RTL when the device locale is Arabic.

Catch regressions with golden tests#

Golden tests are the fastest way to prevent RTL layout drift. Add a golden test for the same widget in LTR and RTL and compare snapshots.

If you want a structured test strategy around this, align it with a testing pyramid. See Flutter testing pyramid: unit, widget, integration, golden.

# Step 5: Date, time, number, and currency formatting#

Hardcoding formats breaks globally. The US uses MM/dd, most of Europe uses dd/MM, and decimal separators vary by locale. Formatting also affects trust in fintech and e-commerce apps, where a wrong currency format can increase support tickets quickly.

Date and time formatting#

Use intl with the active locale:

Dart
import 'package:intl/intl.dart';
 
String formatOrderDate(DateTime dt, String locale) {
  final df = DateFormat.yMMMd(locale);
  return df.format(dt);
}

In a widget:

Dart
final locale = Localizations.localeOf(context).toLanguageTag();
Text(formatOrderDate(order.createdAt, locale));

Number and currency formatting#

Dart
import 'package:intl/intl.dart';
 
String formatPrice(num value, String locale, String currencyCode) {
  final nf = NumberFormat.simpleCurrency(locale: locale, name: currencyCode);
  return nf.format(value);
}

Why this matters: correct formatting reduces user confusion and increases conversion. Baymard Institute’s checkout usability research consistently highlights clarity and trust as conversion drivers, and localized currency presentation is a core part of that clarity.

ℹ️ Note: Keep business logic values in canonical units and format only at the presentation layer. Store 1234.56 as a number, not as a pre-formatted string.

# Step 6: Add CI checks for ARB validity and missing keys#

Localization breaks are expensive because they often reach production unnoticed. A missing key may only show up in one locale, on one screen, behind one feature flag. CI should catch issues the moment an ARB file changes.

The goal is to fail the build when any of these happen:

  • ARB JSON is invalid
  • ICU messages are invalid and cannot be generated
  • Locale files are missing keys compared to the template
  • Generated localization output changes but was not committed

What to validate#

CheckWhy it mattersWhere to run
JSON parse of ARB filesPrevents runtime or generation failuresCI and pre-commit
Key parity with templatePrevents missing strings per localeCI
gen-l10n generationEnsures ICU messages compileCI
No uncommitted generated changesKeeps builds deterministicCI

GitHub Actions workflow example#

Create this workflow file:

YAML
# .github/workflows/l10n-checks.yml
name: L10n checks
 
on:
  pull_request:
    paths:
      - "lib/l10n/**"
      - "l10n.yaml"
      - "pubspec.yaml"
      - ".github/workflows/l10n-checks.yml"
 
jobs:
  l10n:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
 
      - uses: subosito/flutter-action@v2
        with:
          flutter-version: "3.24.0"
          cache: true
 
      - name: Pub get
        run: flutter pub get
 
      - name: Validate ARB JSON and key parity
        run: dart run tool/arb_check.dart
 
      - name: Generate localizations
        run: flutter gen-l10n
 
      - name: Fail if generated files changed
        run: |
          git status --porcelain
          test -z "$(git status --porcelain)"

Why this matters: the last step turns missing generation commits into a hard failure, which prevents subtle mismatches across developer machines and CI.

💡 Tip: If your pipeline already runs Flutter build steps, keep this job separate and fast. A dedicated l10n job usually completes in under 2 minutes on GitHub runners and provides clear feedback on PRs.

ARB validation script with key parity#

Create a small Dart script that checks JSON parsing and enforces that every locale contains all keys from the template. Keep it strict. If you want partial translations, handle that by explicit policy, not by silent omissions.

Dart
// tool/arb_check.dart
import 'dart:convert';
import 'dart:io';
 
void main() {
  final dir = Directory('lib/l10n');
  final files = dir
      .listSync()
      .whereType<File>()
      .where((f) => f.path.endsWith('.arb'))
      .toList();
 
  if (files.isEmpty) {
    stderr.writeln('No ARB files found in lib/l10n');
    exit(1);
  }
 
  final template = File('lib/l10n/app_en.arb');
  final templateJson = jsonDecode(template.readAsStringSync()) as Map;
  final templateKeys = templateJson.keys.where((k) => !k.startsWith('@')).toSet();
 
  var ok = true;
 
  for (final file in files) {
    final map = jsonDecode(file.readAsStringSync()) as Map;
    final keys = map.keys.where((k) => !k.startsWith('@')).toSet();
    final missing = templateKeys.difference(keys);
 
    if (missing.isNotEmpty) {
      ok = false;
      stderr.writeln('Missing keys in ${file.path}: ${missing.join(', ')}');
    }
  }
 
  if (!ok) exit(2);
  stdout.writeln('ARB checks passed for ${files.length} files.');
}

Add it to pubspec.yaml as a dev tool dependency only if you need additional packages. This script uses only dart:convert and dart:io, so it runs without extra dependencies.

Prevent missing translations while still shipping#

If you want to allow untranslated strings temporarily, use a deliberate placeholder policy. For example, enforce that missing strings must exist but may contain a marker like TODO:. Then CI can fail only when a release branch is created, or when TODO: markers remain.

A practical policy table:

StageAllowed in non-template localesCI behavior
Feature branchPlaceholder text like TODO: translateWarn, not fail
Main branchNo placeholdersFail
Release tagNo placeholders and key parity enforcedFail

Implementing warnings versus failures depends on your branching strategy, but the key point is that you decide explicitly.

For broader CI patterns for Flutter apps, including caching and parallel jobs, see Flutter CI/CD: GitHub Actions, Codemagic, Fastlane.

# Step 7: Common pitfalls that cause production localization bugs#

These are the issues we see most often in real Flutter codebases.

Hard-coded left and right assumptions#

Using left and right breaks RTL. Use directional variants throughout your UI primitives, especially in shared components.

If you maintain a UI kit, bake direction-aware spacing into your design system widgets. This pairs well with consistent typography and theming practices described in Flutter design system theming: Material 3, dynamic color, typography.

Formatting with the wrong locale string#

intl formatting expects locale identifiers like en, en_US, or BCP-47 language tags. Use toLanguageTag() for consistency and avoid mixing formats in your code.

Missing placeholder metadata#

Without placeholder types, the generator can infer incorrectly or produce less helpful APIs. Always define placeholders for ICU messages, especially with count, price, or dates.

Not testing non-English locales early#

Even one RTL locale in the app forces layout correctness across the board. Add Arabic early, even if only for smoke testing and golden snapshots.

# Key Takeaways#

  • Use Flutter gen-l10n with ARB files to get strongly typed localization methods and reduce runtime string lookup bugs.
  • Implement plurals and gender with ICU syntax in ARB values, not with widget-side branching.
  • Build RTL safety by using directional padding and alignment APIs and adding at least one RTL locale for continuous testing.
  • Format dates, numbers, and currency with intl using the active locale, keeping raw values in business logic.
  • Add CI checks that validate ARB JSON, enforce key parity with the template, run gen-l10n, and fail on uncommitted generated changes.

# Conclusion#

A reliable localization setup is a mix of correct ICU messages, direction-aware UI code, predictable locale fallbacks, and CI enforcement. If you implement the steps above, you’ll prevent the most common i18n regressions and make translation changes safe to ship continuously.

If you want Samioda to audit your Flutter localization workflow, add RTL and golden coverage, or wire these checks into your pipeline, reach out via our mobile development services and we’ll help you ship multilingual Flutter apps without surprises.

FAQ

Share
A
Adrijan OmićevićFounder & Senior Developer

Founder & Senior Developer at Samioda. 8+ years building React, Next.js, Flutter and n8n automation solutions for clients across Europe.

Need help with your project?

We build custom solutions using the technologies discussed in this article. Senior team, fixed prices.