Skip to main content

Implementing Internationalization

1. Setting Up intl Package

Step Description Action
1 Add intl dependency to pubspec.yaml
dependencies:
  intl: ^0.18.1
2 Run pub get to install the package flutter pub get
3 Create localization files (e.g., intl_en.dart, intl_fr.dart) flutter pub run intl_translation:extract_to_arb --output-dir=lib/l10n lib/main.dart
4 Generate localization classes flutter pub run intl_translation:generate_from_arb --output-dir=lib/l10n --no-use-legacy-code-generator lib/main.dart

Example: Basic localization setup in main.dart

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'l10n/app_localizations.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      locale: Locale('en'),
      supportedLocales: [
        Locale('en'),
        Locale('fr'),
      ],
      localizationsDelegates: [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      home: MyHomePage(),
    );
  }
}

2. Creating ARB Files

ARB (Application Resource Bundle) files are used in Flutter for managing internationalized strings. Each ARB file corresponds to a specific locale and contains key-value pairs of translated text.

Field Description Example
key Unique identifier for the string resource greeting_message
value Translated string in the target language Hello, {name}!
description Optional description for translators A greeting message with user name

Example: Sample ARB File Content

{
  "greeting_message": "Hello, {name}!",
  "greeting_message": "Hello, {name}!",
  "description": "A greeting message with user name"
}
Note: ARB files are JSON-based and must follow strict formatting rules to be correctly parsed by Flutter's internationalization tools.

3. Generating Localizations

Example: Setting up localization in Flutter

// pubspec.yaml
flutter:
  uses-material-design: true
  generate: true

// lib/l10n.yaml
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
Step Description Command
1. Create arb files Define translation keys in ARB format app_en.arb, app_es.arb
2. Configure pubspec.yaml Enable localization generation flutter: generate: true
3. Run localization generator Generate Dart localization files flutter gen-l10n
Note: ARB (Application Resource Bundle) files are JSON-based and support placeholders.
Warning: Ensure all keys are consistent across language files to avoid missing translations.

Example: Using localized strings in code

import 'package:flutter_gen/gen_l10n/app_localizations.dart';

Text(AppLocalizations.of(context)!.welcomeMessage)

4. Using AppLocalizations Class

Property Description Usage
AppLocalizations.of(context) Retrieves the localized strings for the current locale String welcomeMessage = AppLocalizations.of(context).welcome;
AppLocalizationsDelegate Delegate responsible for loading localization files AppLocalizationsDelegate()

Example: Using AppLocalizations in a Widget

import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);
    return Text(localizations.welcomeMessage);
  }
}
Note: Ensure that AppLocalizations is properly initialized in your app's MaterialApp or WidgetsApp.
Warning: If AppLocalizations is not correctly configured, the app will throw a runtime error when trying to access localized strings.

5. Configuring Supported Locales

Property Value Description
supportedLocales [Locale('en', 'US'), Locale('es', 'ES')] List of locales the app supports
localeResolutionCallback (Locale? locale, Iterable<Locale> supportedLocales) => Locale? Function to resolve the app's locale based on device settings

Example: Setting Supported Locales

MaterialApp(
  supportedLocales: [
    const Locale('en', 'US'),
    const Locale('es', 'ES'),
  ],
  localeResolutionCallback: (Locale? locale, Iterable<Locale> supportedLocales) {
    return locale;
  },
)
Note: Ensure all supported locales are defined in your app's localization files.

6. Using Localization Delegates

Property Description Usage
supportedLocales List of locales supported by the app Used in MaterialApp or CupertinoApp to define available languages
localizationsDelegates Delegates for loading localized strings Defines how localization data is loaded and accessed
locale Current app locale Controls which language is displayed

Example: Setting up localization delegates

import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Localization Demo',
      localizationsDelegates: [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('en', ''),
        const Locale('es', ''),
        const Locale('fr', ''),
      ],
      home: MyHomePage(),
    );
  }
}
Note: The AppLocalizations.delegate is generated by the flutter_gen tool and must be included to load custom localized strings.

Key Points

  • localizationsDelegates must include the custom localization delegate (e.g., AppLocalizations.delegate)
  • Global delegates like GlobalMaterialLocalizations.delegate are needed for built-in widgets
  • supportedLocales defines which languages the app supports
  • Localization delegates are responsible for loading and providing localized strings

7. Formatting Dates and Times

Property Values Description
DateFormat DateFormat.yMMMd(), DateFormat.MMMMd() Predefined date formats for various locale requirements
DateFormat.yMMMMd DateFormat.yMMMMd() Full date format like "January 1, 2025"
DateFormat.Hm DateFormat.Hm() 24-hour time format like "14:30"

Example: Formatting Date and Time

import 'package:intl/intl.dart';

void main() {
  final date = DateTime(2025, 1, 1, 14, 30);
  final formattedDate = DateFormat.yMMMMd().format(date);
  final formattedTime = DateFormat.Hm().format(date);

  print(formattedDate); // January 1, 2025
  print(formattedTime); // 14:30
}
Note: Ensure intl package is added to pubspec.yaml.

Example: Custom Date Format

import 'package:intl/intl.dart';

void main() {
  final date = DateTime(2025, 1, 1, 14, 30);
  final customFormat = DateFormat('dd/MM/yyyy – HH:mm');
  print(customFormat.format(date)); // 01/01/2025 – 14:30
}

8. Formatting Numbers and Currency

Property Description Example
NumberFormat Class for formatting numbers according to locale NumberFormat('en_US').format(1234.56)
CurrencyFormat Formats numbers as currency values NumberFormat.currency(locale: 'en_US', name: 'USD').format(1234.56)

Example: Formatting Numbers

import 'package:intl/intl.dart';

void main() {
  final numberFormatter = NumberFormat('###,###.00', 'en_US');
  print(numberFormatter.format(1234567.89)); // Output: 1,234,567.89
}

Example: Formatting Currency

import 'package:intl/intl.dart';

void main() {
  final currencyFormatter = NumberFormat.currency(
    locale: 'en_US',
    name: 'USD',
    symbol: r'
Note: The intl package is required for number and currency formatting in Flutter.

9. Using Intl.message() Method

Property Description Example
Intl.message() Used to mark translatable strings in Flutter apps Intl.message("Hello, World!", desc: "Greeting message")

Example: Basic Usage of Intl.message()

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text(Intl.message("Home"))),
        body: Center(child: Text(Intl.message("Welcome"))),
      ),
    );
  }
}
Note: The Intl.message() method is part of the intl package and requires proper setup for localization.
Warning: Make sure to run flutter pub get and configure the localization files correctly before using Intl.message().

10. Implementing Pluralization and Gender

Feature Description Usage
pluralization Handling different plural forms based on count plural('item', 5)
gender Supporting gender-specific translations gender('user', 'male')

Example: Pluralization in Flutter

import 'package:flutter_gen/gen_l10n/app_localizations.dart';

Text(AppLocalizations.of(context)!.itemsCount(5));

Example: Gender-specific Translation

import 'package:flutter_gen/gen_l10n/app_localizations.dart';

Text(AppLocalizations.of(context)!.userGender('John', 'male'));
Note: Flutter uses intl package for pluralization and gender support. Ensure your locale files are properly configured with plural rules.
, ); print(currencyFormatter.format(1234.56)); // Output: $1,234.56 }

Was this article helpful?