Skip to content

Instantly share code, notes, and snippets.

@maheshj01
Last active June 28, 2020 09:58
Show Gist options
  • Save maheshj01/27d6e82fffdb4205dbd5b2b41e587561 to your computer and use it in GitHub Desktop.
Save maheshj01/27d6e82fffdb4205dbd5b2b41e587561 to your computer and use it in GitHub Desktop.
Steps to Adding locales to a Flutter Application
  1. Add to pubspec.yaml
  • flutter_localization: sdk:flutter
  • intl_translation: ^0.17.10
  • flutter_cupertino_localizations: ^1.0.1
  1. create a lib/locales folder with a lib/locales/locale.dart file and add DemoLocalizationDelegate class and AppLocalizationDelgate class from here

Note: make sure you have imported these libraries in locale.dart

import 'package:intl/intl.dart';
import 'package:flutter/foundation.dart';
  1. create lib/l10n folder and run this command to EXTRACT String from locale.dart to ARB Files

flutter pub run intl_translation:extract_to_arb --output-dir=lib/l10n lib/locale/locale.dart

this command genrates an intl_messages.arb file with the format for each text_message to be translated

The intl_messages.arb file is a JSON format map with one entry for each Intl.message() function defined in main.dart. This file serves as a template for the English and Spanish translations,create these files based on your required locale intl_en.arb and intl_es.arb and paste the intl_messages.arb(template) to each of these files and translate each word according to the locale.

Note:These translations are created by you, the developer.

  1. With the app’s root directory as the current directory, generate intl_messages_.dart for each intl_.arb file and intl_messages_all.dart, which imports all of the messages files

And then run this command to generate the corresponding dart files to your locale.

flutter pub run intl_translation:generate_from_arb \
    --output-dir=lib/l10n --no-use-deferred-loading \
    lib/main.dart lib/l10n/intl_*.arb

e.g to generate dart files for en,de

flutter pub pub run intl_translation:generate_from_arb --output-dir=lib/l10n --no-use-deferred-loading lib/l10n/intl_de.arb lib/l10n/intl_en.arb lib/l10n/intl_nl.arb lib/locale/locale.dart
  • Now keep adding translations(getters) to locale.dart once done run the first command to generate the template(messages_all.arb).
  • And then copy that template to respective .arb file and translate the corresponding strings in the respective locale.
  • finally run the 2nd command to generate the dart files

you can access each word in the UI using

AppLocalizations.of(context).wordKeyName;

Note: Dont forget to add a new language locale code in locale.dart under isSupported method

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment