Easy Localization for Flutter Apps: A Comprehensive Guide

Published on by Flutter News Hub

Easy Localization for Flutter Apps: A Comprehensive Guide

Easy Localization is a powerful library for internationalizing Flutter applications, making it effortless to translate your app into multiple languages. This comprehensive guide will walk you through the setup, usage, and advanced features of Easy Localization to help you create truly globalized apps.

Getting Started

1. Installation:

dependencies:
  easy_localization: ^latest_version

2. Asset Localization: Create a translations folder under assets/ and add your translation files in the desired language codes. Supported formats include JSON, CSV, YAML, and more.

3. Pubspec Configuration:

flutter:
  assets:
    - assets/translations/

4. Easy Localization Widget: In your main widget, wrap your app with the EasyLocalization widget:

runApp(EasyLocalization(
  supportedLocales: [Locale('en', 'US'), Locale('ar', 'DZ')],
  path: 'assets/translations',
  fallbackLocale: Locale('en', 'US'),
  child: MyApp(),
));

Usage

1. Translation: Use tr() to translate strings:

Text('title').tr()

2. Plurals: Translate with pluralization using plural():

Text('money').plural(10.23, format: NumberFormat.compact())

3. Linked Translations: Link translations to avoid duplication:

"helloWorld": "@:example.hello @:example.world"

4. Reset Locale:

RaisedButton(
  onPressed: () => context.resetLocale(),
  child: Text(LocaleKeys.reset_locale).tr(),
)

Advanced Features

1. Code Generation: Generate localization keys and loader classes for your translation files:

flutter pub run easy_localization:generate -s my_file.json -o loader.g.dart

2. Localization Asset Loader: Use custom asset loaders to load translations from external modules or packages:

extraAssetLoaders: [
  TranslationsLoader(packageName: 'package_example'),
],

3. Logger: Customize the Easy Localization logger for debugging and error handling:

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

4. Extensions: Use extensions for convenient locale handling:

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

Benefits of Easy Localization:

  • Easy translation management
  • Supports various localization formats
  • Built-in pluralization and gender handling
  • Code generation for faster development
  • Customizable logger for debugging
  • Supports RTL and LTR languages

Conclusion

Easy Localization is an indispensable tool for internationalizing Flutter apps, providing a comprehensive solution that makes it easy to create multilingual applications. By following the steps and leveraging the advanced features outlined in this guide, you can effectively translate your app into multiple languages and reach a wider audience.

Flutter News Hub