easy_localization

repository·develop·Indexed 21 days ago

https://github.com/aissat/easy_localization

A fast internationalization library for Flutter apps supporting multiple file formats (JSON, CSV, Yaml, XML). It handles plurals, gender, and RTL locales, and persists locale changes to device storage. The repository also includes easy_logger, a logging library for Flutter with configurable build modes, message levels, and custom printer functions.

Tokens
11.2K
Snippets
42
Records
51
Agent score
77%

What's inside easy_localization

  1. Split translations into multiple files

    develop

    To keep JSON files maintainable, you can link external files. Use the :/ prefix followed by the file path, relative to your translations directory.

    Note: Ensure all linked files (or their containing folders) are added to your pubspec.yaml assets.

    {
      "errors": ":/errors.json",
      "validation": ":/validation.json",
      "notifications": ":/notifications.json"
    }
  2. Link translations using `@:`

    develop

    You can link one translation key to another by prefixing the value with @: followed by the full key path. This allows you to reuse existing translations.

    Formatting linked translations

    You can apply case modifiers to linked messages using the @.modifier:key syntax:

    • upper: Uppercase all characters.
    • lower: Lowercase all characters.
    • capitalize: Capitalize the first character.
    {
      "example": {
        "hello": "Hello",
        "world": "World!",
        "helloWorld": "@:example.hello @:example.world"
      },
      "emptyNameError": "Please fill in your @.lower:example.fullName"
    }
  3. Customize the printer function

    develop

    You can replace the default logging output by providing a custom printer function. The function signature must accept an Object, and optional named parameters name (String), stackTrace (StackTrace), and level (LevelMessages).

    EasyLogPrinter customLogPrinter = (
      Object object, {
      String name,
      StackTrace stackTrace,
      LevelMessages level,
    }) {
      print('$name: ${object.toString()}');
    };
    
    // Option 1: Pass to constructor
    final EasyLogger logger = EasyLogger(
      printer: customLogPrinter,
    );
    
    // Option 2: Assign to existing instance
    logger.printer = customLogPrinter;
  4. Generate localization keys for type-safe access

    develop

    If you want to avoid manual string keys and benefit from code editor autocompletion, you can generate a LocaleKeys class.

    1. Run the following command: flutter pub run easy_localization:generate -f keys -o locale_keys.g.dart
    2. Import the generated file: import 'generated/locale_keys.g.dart';

    Usage: You can use the generated keys to translate strings or widgets directly.

    import 'generated/locale_keys.g.dart';
    
    // As a String
    print(LocaleKeys.title.tr());
    
    // As a Widget
    Text(LocaleKeys.title).tr();
  5. Configure iOS for localization

    develop

    For translations to function on iOS, you must explicitly add your supported locales to the ios/Runner/Info.plist file using the CFBundleLocalizations key.

    <key>CFBundleLocalizations</key>
    <array>
    	<string>en</string>
    	<string>nb</string>
    </array>
  6. Customize iOS Launch Screen Assets

    develop

    To customize the launch screen for your iOS application, you can either replace the image files directly in the ios/Runner/Assets.xcassets/LaunchImage.imageset/ directory or use Xcode for a visual approach.

    Using Xcode:

    1. Open your Flutter project's iOS workspace using the command: open ios/Runner.xcworkspace.
    2. In the Xcode Project Navigator, select Runner/Assets.xcassets.
    3. Drag and drop your desired image assets into the asset catalog.
    open ios/Runner.xcworkspace
  7. Install easy_localization

    develop

    To use easy_localization in your Flutter project, add the package to your pubspec.yaml dependencies. You must also declare your translation assets directory in the flutter.assets section so they are bundled with your application.

    dependencies:
      easy_localization: <last_version>
    
    flutter:
      assets:
        - assets/translations/
  8. Organize translation files

    develop

    Create a folder for your translations and name the files using either the language code or the full locale code.

    File naming patterns:

    • {languageCode}.{ext} (e.g., en.json)
    • {languageCode}-{countryCode}.{ext} (e.g., en-US.json)

    Example structure:

    assets
    └── translations
        ├── en.json
        └── en-US.json 
    assets
    └── translations
        ├── en.json
        └── en-US.json 
  9. Initialize the Easy Localization library

    develop

    Before calling runApp, you must ensure the library is initialized. This requires calling WidgetsFlutterBinding.ensureInitialized() followed by await EasyLocalization.ensureInitialized() in your main function.

    void main() async{
      // ...
      // Needs to be called so that we can await for EasyLocalization.ensureInitialized();
      WidgetsFlutterBinding.ensureInitialized();
    
      await EasyLocalization.ensureInitialized();
      // ...
      runApp(....)
      // ...
    }
  10. Customize build modes and message levels at runtime

    develop

    You can modify which Flutter build modes or message levels are active by updating the properties on your logger instance.

    // Only allow logging in debug and profile modes
    logger.enableBuildModes = [BuildMode.debug, BuildMode.profile];
    
    // Disable all logging by clearing enabled levels
    logger.enableLevels = [];
    
    // Show only error messages
    logger.enableLevels = [LevelMessages.error];
  11. Generate a localization asset loader

    develop

    To improve performance and avoid runtime file loading, you can use code generation to create a CodegenLoader. This supports only .json files.

    1. Run the generation command in your project root: flutter pub run easy_localization:generate
    2. Import the generated file and use CodegenLoader() in your EasyLocalization widget configuration.

    CLI Arguments for generation:

    ArgumentShortDefaultDescription
    --help-hHelp info
    --source-dir-Sresources/langsFolder containing localization files
    --source-file-sFirst fileFile to use for localization
    --output-dir-Olib/generatedOutput folder 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 objects except for plural() and gender() keywords
    import 'generated/codegen_loader.g.dart';
    
    void main() {
      runApp(EasyLocalization(
        child: MyApp(),
        supportedLocales: [Locale('en', 'US'), Locale('ar', 'DZ')],
        path: 'resources/langs',
        assetLoader: CodegenLoader(),
      ));
    }