Skip to content

Repository files navigation

Easy and Fast internationalization for your Flutter Apps

Pub VersionlikeslikeslikesCode Climate issuesGitHub closed issuesGitHub contributorsGitHub repo sizeGitHub forksGitHub starsCoveralls github branchGitHub Workflow StatusCodeFactor GradeGitHub licenseSponsorsPRs Welcome

Why easy_localization?

  • 🚀 Easy translations for many languages
  • 🔌 Load translations as JSON, CSV, Yaml, Xml using Easy Localization Loader
  • 💾 React and persist to locale changes
  • ⚡ Supports plural, gender, nesting, RTL locales and more
  • ↩️ Fallback locale keys redirection
  • ⁉️ Error widget for missing translations
  • ❤️ Extension methods on Text and BuildContext
  • 💻 Code generation for localization files and keys.
  • 🛡️ Null safety
  • 🖨️ Customizable logger.

Getting Started

🔩 Installation

Add to your pubspec.yaml:

dependencies:
easy_localization: <last_version>

Create folder and add translation files like this

assets
└── translations
├── {languageCode}.{ext} //only language code
└── {languageCode}-{countryCode}.{ext} //or full locale code

Example:

assets
└── translations
├── en.json
└── en-US.json 

Declare your assets localization directory in pubspec.yaml:

flutter:
assets:
- assets/translations/

🔌 Loading translations from other resources

You can use JSON,CSV,HTTP,XML,Yaml files, etc.

See Easy Localization Loader for more info.

⚠️ Note on iOS

For translation to work on iOS you need to add supported locales to ios/Runner/Info.plist as described here.

Example:

<key>CFBundleLocalizations</key>
<array>
<string>en</string>
<string>nb</string>
</array>

⚙️ Configuration app

Add EasyLocalization widget like in example

import'package:flutter/material.dart';
import'package:flutter_localizations/flutter_localizations.dart';
import'package:easy_localization/easy_localization.dart';
voidmain() async {
WidgetsFlutterBinding.ensureInitialized();
awaitEasyLocalization.ensureInitialized();
runApp(
EasyLocalization(
supportedLocales: [Locale('en', 'US'), Locale('de', 'DE')],
path:'assets/translations', // <-- change the path of the translation files 
fallbackLocale:Locale('en', 'US'),
child:MyApp()
),
);
}
classMyAppextendsStatelessWidget {
@overrideWidgetbuild(BuildContext context) {
returnMaterialApp(
localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: context.locale,
home:MyHomePage()
);
}
}

Full example

📜 Easy localization widget properties

PropertiesRequiredDefaultDescription
keyfalseWidget key.
childtruePlace for your main page widget.
supportedLocalestrueList of supported locales.
pathtruePath to your folder with localization files.
assetLoaderfalseRootBundleAssetLoader()Class loader for localization files. You can use custom loaders from Easy Localization Loader or create your own class.
fallbackLocalefalseReturns the locale when the locale is not in the list supportedLocales.
startLocalefalseOverrides device locale.
saveLocalefalsetrueSave locale in device storage.
useFallbackTranslationsfalsefalseIf a localization key is not found in the locale file, try to use the fallbackLocale file.
useOnlyLangCodefalsefalseTrigger for using only language code for reading localization files.

Example:
en.json //useOnlyLangCode: true
en-US.json //useOnlyLangCode: false
errorWidgetfalseFutureErrorWidget()Shows a custom error widget when an error occurs.

Usage

🔥 Initialize library

Call EasyLocalization.ensureInitialized() in your main before runApp.

voidmain() async{
// ...// Needs to be called so that we can await for EasyLocalization.ensureInitialized();WidgetsFlutterBinding.ensureInitialized();
awaitEasyLocalization.ensureInitialized();
// ...runApp(....)
// ...
}

🔥 Change or get locale

Easy localization uses extension methods [BuildContext] for access to locale.

It's the easiest way change locale or get parameters 😉.

ℹ️ No breaking changes, you can use old the static method EasyLocalization.of(context)

Example:

context.setLocale(Locale('en', 'US'));
print(context.locale.toString());

🔥 Translate tr()

Main function for translate your language keys

You can use extension methods of [String] or [Text] widget, you can also use tr() as a static function.

Text('title').tr() //Text widgetprint('title'.tr()); //Stringvar title =tr('title') //Static function

Arguments:

NameTypeDescription
argsList<String>List of localized strings. Replaces {} left to right
namedArgsMap<String, String>Map of localized strings. Replaces the name keys {key_name} according to its name
genderStringGender switcher. Changes the localized string based on gender string

Example:

{
"msg":"{} are written in the {} language",
"msg_named":"Easy localization is written in the {lang} language",
"msg_mixed":"{} are written in the {lang} language",
"gender":{
"male":"Hi man ;) {}",
"female":"Hello girl :) {}",
"other":"Hello {}"
}
}
// argsText('msg').tr(args: ['Easy localization', 'Dart']),
// namedArgsText('msg_named').tr(namedArgs: {'lang':'Dart'}),
// args and namedArgsText('msg_mixed').tr(args: ['Easy localization'], namedArgs: {'lang':'Dart'}),
// genderText('gender').tr(gender: _gender ?"female":"male"),

🔥 Plurals plural()

You can translate with pluralization. To insert a number in the translated string, use {}. Number formatting supported, for more information read NumberFormat class documentation.

You can use extension methods of [String] or [Text] widget, you can also use plural() as a static function.

Arguments:

NameTypeDescription
valuenumNumber value for pluralization
argsList<String>List of localized strings. Replaces {} left to right
namedArgsMap<String, String>Map of localized strings. Replaces the name keys {key_name} according to its name
nameStringName of number value. Replaces {$name} to value
formatNumberFormatFormats a numeric value using a NumberFormat class

Example:

{
"day": {
"zero":"{} дней",
"one": "{} день",
"two": "{} дня",
"few": "{} дня",
"many": "{} дней",
"other": "{} дней"
},
"money": {
"zero": "You not have money",
"one": "You have {} dollar",
"many": "You have {} dollars",
"other": "You have {} dollars"
},
"money_args": {
"zero": "{} has no money",
"one": "{} has {} dollar",
"many": "{} has {} dollars",
"other": "{} has {} dollars"
},
"money_named_args": {
"zero": "{name} has no money",
"one": "{name} has {money} dollar",
"many": "{name} has {money} dollars",
"other": "{name} has {money} dollars"
}
}

⚠️ Key "other" required!

//Text widget with formatText('money').plural(1000000, format:NumberFormat.compact(locale: context.locale.toString())) // output: You have 1M dollars//Stringprint('day'.plural(21)); // output: 21 день//Static functionvar money =plural('money', 10.23) // output: You have 10.23 dollars//Static function with argumentsvar money =plural('money_args', 10.23, args: ['John', '10.23']) // output: John has 10.23 dollars//Static function with named argumentsvar money =plural('money_named_args', 10.23, namedArgs: {'name':'Jane', 'money':'10.23'}) // output: Jane has 10.23 dollarsvar money =plural('money_named_args', 10.23, namedArgs: {'name':'Jane'}, name:'money') // output: Jane has 10.23 dollars

🔥 Linked translations:

If there's a translation key that will always have the same concrete text as another one you can just link to it. To link to another translation key, all you have to do is to prefix its contents with an @: sign followed by the full name of the translation key including the namespace you want to link to.

Example:

{
..."example": {
"hello": "Hello",
"world": "World!",
"helloWorld": "@:example.hello @:example.world"
}
...
}
print('example.helloWorld'.tr()); //Output: Hello World!

You can also do nested anonymous and named arguments inside the linked messages.

Example:

{
..."date": "{currentDate}.",
"dateLogging": "INFO: the date today is @:date"...
}
print('dateLogging'.tr(namedArguments: {'currentDate':DateTime.now().toIso8601String()})); //Output: INFO: the date today is 2020-11-27T16:40:42.657.

Formatting linked translations:

Formatting linked locale messages If the language distinguishes cases of character, you may need to control the case of the linked locale messages. Linked messages can be formatted with modifier @.modifier:key

The below modifiers are available currently.

  • upper: Uppercase all characters in the linked message.
  • lower: Lowercase all characters in the linked message.
  • capitalize: Capitalize the first character in the linked message.

Example:

{
..."example": {
"fullName": "Full Name",
"emptyNameError": "Please fill in your @.lower:example.fullName"
}
...
}

Output:

print('example.emptyNameError'.tr()); //Output: Please fill in your full name

🔥 Reset locale resetLocale()

Reset locale to device locale

Example:

RaisedButton(
onPressed: (){
context.resetLocale();
},
child:Text(LocaleKeys.reset_locale).tr(),
)

🔥 Get device locale deviceLocale

Get device locale

Example:

print(${context.deviceLocale.toString()}) // OUTPUT: en_US

🔥 Delete save locale deleteSaveLocale()

Clears a saved locale from device storage

Example:

RaisedButton(
onPressed: (){
context.deleteSaveLocale();
},
child:Text(LocaleKeys.reset_locale).tr(),
)

🔥 Get Easy localization widget properties

At any time, you can take the main properties of the Easy localization widget using [BuildContext].

Are supported: supportedLocales, fallbackLocale, localizationDelegates.

Example:

print(context.supportedLocales); // output: [en_US, ar_DZ, de_DE, ru_RU]print(context.fallbackLocale); // output: en_US

💻 Code generation

Code generation supports only json files, for more information run in terminal flutter pub run easy_localization:generate -h

Command line arguments

ArgumentsShortDefaultDescription
--help-hHelp info
--source-dir-Sresources/langsFolder containing localization files
--source-file-sFirst fileFile to use for localization
--output-dir-Olib/generatedOutput folder stores for the generated file
--output-file-ocodegen_loader.g.dartOutput file name
--format-fjsonSupport json or keys formats
--[no-]skip-unnecessary-keys-ufalseIgnores keys defining nested object except for pluarl(), gender() keywords.

🔌 Localization asset loader class

Steps:

  1. Open your terminal in the folder's path containing your project
  2. Run in terminal flutter pub run easy_localization:generate
  3. Change asset loader and past import.
import'generated/codegen_loader.g.dart';
...
voidmain(){
runApp(EasyLocalization(
child:MyApp(),
supportedLocales: [Locale('en', 'US'), Locale('ar', 'DZ')],
path:'resources/langs',
assetLoader:CodegenLoader()
));
}
...
  1. All done!

🔑 Localization keys

If you have many localization keys and are confused, key generation will help you. The code editor will automatically prompt keys

Steps:

  1. Open your terminal in the folder's path containing your project
  2. Run in terminal flutter pub run easy_localization:generate -f keys -o locale_keys.g.dart
  3. Past import.
import'generated/locale_keys.g.dart';
  1. All done!

How to use generated keys:

print(LocaleKeys.title.tr()); //String//orText(LocaleKeys.title).tr(); //Widget

🖨️ Logger

[Easy Localization] logger based on [Easy Logger]

You can customize logger for you project

Show only lost keys message

Lost translations keys logged like warning messages. Change [Easy Logger] level for display only errors and warnings.

EasyLocalization.logger.enableLevels = [LevelMessages.error, LevelMessages.warning];

Logger off

For disable logger, change Build Modes in [Easy Logger] to empty List;

EasyLocalization.logger.enableBuildModes = [];

Catching logger messages

For catching logger messages you need override default printer function.

EasyLogPrinter customLogPrinter = (
Object object, {
String name,
StackTrace stackTrace,
LevelMessages level,
}) {
///Your functionprint('$name: ${object.toString()}');
};
/// override printer to customEasyLocalization.logger.printer = customLogPrinter;

Read more about Easy Logger

➕ Extensions helpers

String to locale

'en_US'.toLocale(); // Locale('en', 'US')//with custom separator'en|US'.toLocale(separator:'|') // Locale('en', 'US')

Locale to String with separator

Locale('en', 'US').toStringWithSeparator(separator:'|') // en|US

Screenshots

Arabic RTLEnglish LTRError widget
Arabic RTLEnglish LTRError widget

Donations

We need your support. Projects like this can not be successful without support from the community. If you find this project useful, and would like to support further development and ongoing maintenance, please consider donating.

Sponsors

Contributors thanks

contributors

About

Easy and Fast internationalizing your Flutter Apps

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages