### Named Arguments Usage Source: https://pub.dev/packages/easy_localization/changelog Example of defining named arguments in JSON and using them in the UI. ```json "msg_named": "{} are written in the {lang} language", ``` ```dart Text(LocaleKeys.msg_named).tr(namedArgs: {'lang': 'Dart'}, args: ['Easy localization']), ``` -------------------------------- ### Custom Asset Loaders Source: https://pub.dev/packages/easy_localization/changelog Configuration examples for loading different file formats like CSV, YAML, and XML. ```dart path: 'resources/langs/langs.csv', assetLoader: CsvAssetLoader(), ``` ```dart path: 'resources/langs', assetLoader: YamlAssetLoader(), ``` ```dart path: 'resources/langs/langs.yaml', assetLoader: YamlSingleAssetLoader(), ``` ```dart path: 'resources/langs', assetLoader: XmlAssetLoader(), ``` ```dart path: 'resources/langs/langs.xml', assetLoader: XmlSingleAssetLoader(), ``` -------------------------------- ### Supported Locales Configuration Source: https://pub.dev/packages/easy_localization/changelog Example of defining supported locales in the EasyLocalization widget configuration. ```dart supportedLocales: [ Locale('en', 'US'), Locale('ar', 'DZ'), Locale('ar','DZ'),localeFromString('ar_DZ') ] ``` -------------------------------- ### Install package via Flutter CLI Source: https://pub.dev/packages/easy_localization/install Use this command in your terminal to add the package to your project dependencies. ```bash $ flutter pub add easy_localization ``` -------------------------------- ### Translation Arguments Example Source: https://pub.dev/packages/easy_localization JSON structure for translation keys supporting arguments, named arguments, and gender switching. ```json { "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 {}" } } ``` -------------------------------- ### Localization Keys Generation Source: https://pub.dev/packages/easy_localization/changelog Example of JSON structure and the resulting generated Dart class for static keys. ```json { "msg_named": "{} مكتوبة باللغة {lang}", } ``` ```dart abstract class LocaleKeys { static const msg_named = 'msg_named'; } ``` ```dart Text(LocaleKeys.msg_named).tr(namedArgs: {'lang': 'Dart'}, args: ['Easy localization']), ``` -------------------------------- ### Static Analysis: Deprecated textScaleFactor Source: https://pub.dev/packages/easy_localization/score Example of the deprecated textScaleFactor usage found in lib/src/public_ext.dart. ```dart ╷ 38 │ textScaleFactor: textScaleFactor, │ ^^^^^^^^^^^^^^^ ╵ ``` -------------------------------- ### Locale Management Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Methods for getting and setting the current application locale using BuildContext extensions. ```APIDOC ## context.setLocale(Locale) ### Description Updates the current application locale. ### Parameters - **locale** (Locale) - The new locale to apply. ## context.locale ### Description Returns the current locale as a string. ``` -------------------------------- ### Get Device Locale Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Retrieve the current device locale string. ```dart print(context.deviceLocale.toString()) // OUTPUT: en_US ``` -------------------------------- ### Static Analysis: Dangling Library Doc Comment Source: https://pub.dev/packages/easy_localization/score Example of a dangling library doc comment issue found in lib/src/plural_rules.dart. ```dart ╷ 5 │ /// Provides locale-specific plural rules. Based on pluralrules.js from Closure. │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ╵ ``` -------------------------------- ### Nested Translation Configuration and Usage Source: https://pub.dev/packages/easy_localization/changelog Example JSON structure for nested keys and the corresponding Flutter Text widget implementation using AppLocalizations. ```json { "title": "Hello", "msg": "Hello {} in the {} world ", "clickMe": "Click me", "profile": { "reset_password": { "label": "Reset Password", "username": "Username", "password": "password" } }, "clicked": { "zero": "You clicked {} times!", "one": "You clicked {} time!", "other": "You clicked {} times!" } } ``` ```dart new Text( AppLocalizations.of(context).tr('profile.reset_password.title'), ), ``` -------------------------------- ### Initialize EasyLocalization Source: https://pub.dev/packages/easy_localization/changelog Demonstrates the initialization structure for EasyLocalization in version 2.0.0. ```dart // Now V2.0.0 runApp(EasyLocalization( child: MyApp(), ... )); // after V2.0.0 runApp(EasyLocalization( child: MyApp(), ... )); ... class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { var data = EasyLocalizationProvider.of(context).data; return EasyLocalizationProvider(...); }} ``` -------------------------------- ### EasyLocalization.ensureInitialized() Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Initializes the localization library. This must be called in the main function before runApp. ```APIDOC ## EasyLocalization.ensureInitialized() ### Description Initializes the EasyLocalization library. This method must be awaited in the main function before calling runApp to ensure localization resources are ready. ### Usage ```dart await EasyLocalization.ensureInitialized(); ``` ``` -------------------------------- ### EasyLocalization.ensureInitialized() Source: https://pub.dev/packages/easy_localization Initializes the EasyLocalization library. This must be called before runApp in the main function. ```APIDOC ## EasyLocalization.ensureInitialized() ### Description Initializes the library to ensure localization data is ready for use. ### Usage ```dart await EasyLocalization.ensureInitialized(); ``` ``` -------------------------------- ### Initialize EasyLocalization with CodegenLoader Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Configure the main application entry point to use the generated CodegenLoader for localization assets. ```dart import 'generated/codegen_loader.g.dart'; ... void main(){ runApp(EasyLocalization( child: MyApp(), supportedLocales: [Locale('en', 'US'), Locale('ar', 'DZ')], path: 'resources/langs', assetLoader: CodegenLoader() )); } ... ``` -------------------------------- ### Code Generation CLI Source: https://pub.dev/packages/easy_localization/changelog Command line interface usage for generating localization files. ```bash $ flutter pub run easy_localization:generate -h -s, --source-dir Source folder contains all string json files (defaults to "resources/langs") -O, --output-dir Output folder stores generated file (defaults to "lib/generated") -o, --output-file Output file name (defaults to "codegen_loader.g.dart") -f, --format Support json, dart formats [json (default), keys] ``` ```bash flutter pub run easy_localization:generate -f keys -o locale_keys.g.dart ``` ```bash flutter pub run easy_localization:generate ``` -------------------------------- ### Configure iOS Info.plist Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Add supported locales to the iOS configuration file to enable localization. ```xml CFBundleLocalizations en nb ``` -------------------------------- ### Initialize Easy Localization Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Call ensureInitialized before running the application to prepare the localization settings. ```dart void main() async{ // ... // Needs to be called so that we can await for EasyLocalization.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized(); await EasyLocalization.ensureInitialized(); // ... runApp(....) // ... } ``` -------------------------------- ### Pluralization with Arguments Source: https://pub.dev/packages/easy_localization/changelog Demonstrates the usage of the plural function with positional and named arguments. ```dart var money = plural('money_args', 10.23, args: ['John', '10.23']) // output: John has 10.23 dollars ``` -------------------------------- ### Import generated locale keys Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Include the generated locale_keys.g.dart file to enable IDE autocompletion for translation keys. ```dart import 'generated/locale_keys.g.dart'; ``` -------------------------------- ### Declare assets in pubspec.yaml Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Register the localization assets directory in your project configuration. ```yaml flutter: assets: - assets/translations/ ``` -------------------------------- ### Use Context-Aware Localization Source: https://pub.dev/packages/easy_localization/changelog Usage of tr and plural methods with context support. ```dart tr("key", context: context), plural("key", 1 , context: context), ``` -------------------------------- ### Use String Extensions Source: https://pub.dev/packages/easy_localization/changelog Localization methods accessed via String extensions introduced in version 1.4.1. ```dart // after 1.4.1 Text('title'.tr()), Text('switch'.tr( gender: _gender ? "female" : "male")), Text('counter'.plural(counter)), ``` -------------------------------- ### Define translation file structure Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Organize translation files within the assets directory using language or locale codes. ```text assets └── translations ├── {languageCode}.{ext} //only language code └── {languageCode}-{countryCode}.{ext} //or full locale code ``` ```text assets └── translations ├── en.json └── en-US.json ``` -------------------------------- ### Initialize easy_localization in main.dart Source: https://pub.dev/packages/easy_localization/example Configures the EasyLocalization widget at the root of the application to manage supported locales and asset loading. ```dart import 'package:easy_localization/easy_localization.dart'; //import 'package:easy_localization_loader/easy_localization_loader.dart'; // import custom loaders import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'generated/locale_keys.g.dart'; import 'lang_view.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await EasyLocalization.ensureInitialized(); runApp(EasyLocalization( supportedLocales: [ Locale('en', 'US'), Locale('ar', 'DZ'), Locale('de', 'DE'), Locale('ru', 'RU') ], path: 'resources/langs', child: MyApp(), // fallbackLocale: Locale('en', 'US'), // startLocale: Locale('de', 'DE'), // saveLocale: false, // useOnlyLangCode: true, // ignorePluralRules: false, // optional assetLoader default used is RootBundleAssetLoader which uses flutter's assetloader // install easy_localization_loader for enable custom loaders // assetLoader: RootBundleAssetLoader() // assetLoader: HttpAssetLoader() // assetLoader: FileAssetLoader() // assetLoader: CsvAssetLoader() // assetLoader: YamlAssetLoader() //multiple files // assetLoader: YamlSingleAssetLoader() //single file // assetLoader: XmlAssetLoader() //multiple files // assetLoader: XmlSingleAssetLoader() //single file // assetLoader: CodegenLoader() )); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( localizationsDelegates: context.localizationDelegates, supportedLocales: context.supportedLocales, locale: context.locale, theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Easy localization'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State { int counter = 0; bool _gender = true; void incrementCounter() { setState(() { counter++; }); } void switchGender(bool val) { setState(() { _gender = val; }); } ``` -------------------------------- ### Translation with Arguments Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Pass arguments or named arguments to replace placeholders in localized strings. ```json { "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 {}" } } ``` ```dart // args Text('msg').tr(args: ['Easy localization', 'Dart']), // namedArgs Text('msg_named').tr(namedArgs: {'lang': 'Dart'}), // args and namedArgs Text('msg_mixed').tr(args: ['Easy localization'], namedArgs: {'lang': 'Dart'}), // gender Text('gender').tr(gender: _gender ? "female" : "male"), ``` -------------------------------- ### Use Text Widget Extensions Source: https://pub.dev/packages/easy_localization/changelog Localization methods applied directly to Text widgets via extensions. ```dart // after 1.4.0 Text('switch').tr( gender: _gender ? "female" : "male"), Text('counter').plural(counter), ``` -------------------------------- ### Locale Extension Method Source: https://pub.dev/packages/easy_localization/changelog Use the BuildContext extension to change the application locale. ```dart context.locale = locale; ``` -------------------------------- ### Configure extraAssetLoaders for multi-module projects Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Include localization assets from external modules or packages by providing a list of TranslationsLoader instances to the extraAssetLoaders parameter. ```dart void main(){ runApp(EasyLocalization( child: MyApp(), supportedLocales: [Locale('en', 'US'), Locale('ar', 'DZ')], path: 'resources/langs', assetLoader: CodegenLoader() extraAssetLoaders: [ TranslationsLoader(packageName: 'package_example_1'), TranslationsLoader(packageName: 'package_example_2'), ], )); } ``` -------------------------------- ### Configure Plural Rules Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Set ignorePluralRules to false during initialization to enable support for 'few' and 'many' plural categories. ```dart EasyLocalization( ignorePluralRules: false, // Set this line to false to enable 'few' and 'many' plural categories supportedLocales: [Locale('en', 'US'), Locale('de', 'DE')], path: 'assets/translations', fallbackLocale: Locale('en', 'US'), child: MyApp() ) ``` -------------------------------- ### tr() Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Translates language keys using static functions or BuildContext extensions. ```APIDOC ## tr(key) ### Description Translates a given language key. Can be used as a static function, a String extension, or a Text widget extension. ### Parameters - **key** (String) - The translation key. - **args** (List) - Optional. Replaces {} placeholders. - **namedArgs** (Map) - Optional. Replaces {key_name} placeholders. - **gender** (String) - Optional. Selects translation based on gender. ``` -------------------------------- ### Audit missing translation keys Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Run the audit command to identify keys used in the application code that are missing from the translation files. ```bash flutter pub run easy_localization:audit ``` -------------------------------- ### MIT License Text Source: https://pub.dev/packages/easy_localization/license The standard MIT License terms applicable to the easy_localization software. ```text MIT License Copyright (c) 2018 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` -------------------------------- ### Link Translation Keys Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Reference other translation keys using the @: prefix within JSON translation files. ```json { ... "example": { "hello": "Hello", "world": "World!", "helloWorld": "@:example.hello @:example.world" } ... } ``` ```dart print('example.helloWorld'.tr()); //Output: Hello World! ``` -------------------------------- ### Link Translations with Arguments Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Pass named arguments to linked translation keys that contain placeholders. ```json { ... "date": "{currentDate}.", "dateLogging": "INFO: the date today is @:date" ... } ``` ```dart print('dateLogging'.tr(namedArguments: {'currentDate': DateTime.now().toIso8601String()})); //Output: INFO: the date today is 2020-11-27T16:40:42.657. ``` -------------------------------- ### Import package in Dart Source: https://pub.dev/packages/easy_localization/install Include this import statement at the top of your Dart files to access the library functionality. ```dart import 'package:easy_localization/easy_localization.dart'; ``` -------------------------------- ### Define pluralization keys Source: https://pub.dev/packages/easy_localization/changelog JSON structure for defining pluralization rules. ```json { "text": { "day": { "zero":"{} дней", "one": "{} день", "two": "{} дня", "few": "{} дня", "many": "{} дней", "other": "{} дней" } } } ``` ```json { "text": { "day": { "zero": "day", "one": "day", "other": "days" } } } ``` -------------------------------- ### Locale Management Source: https://pub.dev/packages/easy_localization Methods to change or retrieve the current application locale using BuildContext extensions. ```APIDOC ## context.setLocale(Locale) ### Description Updates the current application locale. ### Parameters - **locale** (Locale) - Required - The locale to set. ## context.locale ### Description Retrieves the current locale. ``` -------------------------------- ### plural() Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Handles pluralization based on numeric values. ```APIDOC ## plural(key, value) ### Description Translates a key based on a numeric value for pluralization rules. ### Parameters - **key** (String) - The translation key. - **value** (num) - The number used for pluralization. - **args** (List) - Optional. Replaces {} placeholders. - **namedArgs** (Map) - Optional. Replaces {key_name} placeholders. - **name** (String) - Optional. Replaces {$name} with the value. - **format** (NumberFormat) - Optional. Formats the numeric value. ``` -------------------------------- ### Add dependency to pubspec.yaml Source: https://pub.dev/packages/easy_localization/install Manually add this entry to your pubspec.yaml file to define the package dependency. ```yaml dependencies: easy_localization: ^3.0.8 ``` -------------------------------- ### Translate Strings Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Translate keys using context extensions, widget extensions, or static functions. Note that static functions outside of build methods may not trigger UI updates. ```dart Text(context.tr('title')) ``` ```dart Text('title').tr() //Text widget print('title'.tr()); //String var title = tr('title') //Static function ``` -------------------------------- ### Implement Localization in Flutter Scaffold Source: https://pub.dev/packages/easy_localization/example Uses the .tr() extension and plural() methods to display localized strings, handle gender-specific arguments, and manage locale state. ```dart @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(LocaleKeys.title).tr(), actions: [ TextButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (_) => LanguageView(), fullscreenDialog: true), ); }, child: Icon( Icons.language, color: Colors.white, ), ), ], ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Spacer( flex: 1, ), Text( LocaleKeys.gender_with_arg, style: TextStyle( color: Colors.grey.shade600, fontSize: 19, fontWeight: FontWeight.bold), ).tr(args: ['aissat'], gender: _gender ? 'female' : 'male'), Text( tr(LocaleKeys.gender, gender: _gender ? 'female' : 'male'), style: TextStyle( color: Colors.grey.shade600, fontSize: 15, fontWeight: FontWeight.bold), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ FaIcon(FontAwesomeIcons.male), Switch(value: _gender, onChanged: switchGender), FaIcon(FontAwesomeIcons.female), ], ), Spacer( flex: 1, ), Text(LocaleKeys.msg).tr(args: ['aissat', 'Flutter']), Text(LocaleKeys.msg_named) .tr(namedArgs: {'lang': 'Dart'}, args: ['Easy localization']), Text(LocaleKeys.clicked).plural(counter), TextButton( onPressed: () { incrementCounter(); }, child: Text(LocaleKeys.clickMe).tr(), ), SizedBox( height: 15, ), Text( plural(LocaleKeys.amount, counter, format: NumberFormat.currency( locale: Intl.defaultLocale, symbol: '€')), style: TextStyle( color: Colors.grey.shade900, fontSize: 18, fontWeight: FontWeight.bold)), SizedBox( height: 20, ), ElevatedButton( onPressed: () { context.resetLocale(); }, child: Text(LocaleKeys.reset_locale).tr(), ), Spacer( flex: 1, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: incrementCounter, child: Text('+1'), ), ); } } ``` -------------------------------- ### Refactor Localization Calls Source: https://pub.dev/packages/easy_localization/changelog Comparison of localization method calls before and after the 1.4.0 refactor. ```dart // after 1.4.0 Text( tr('switch', gender: _gender ? "female" : "male"), ), ``` ```dart // before 1.4.0 Text( AppLocalizations.of(context).tr('switch', gender: _gender ? "female" : "male"), ), ``` -------------------------------- ### Apply Pluralization Source: https://pub.dev/packages/easy_localization Use plural() to handle numeric variations in translations, ensuring the 'other' key is defined. ```dart //Text widget with format Text('money').plural(1000000, format: NumberFormat.compact(locale: context.locale.toString())) // output: You have 1M dollars //String print('day'.plural(21)); // output: 21 день //Static function var money = plural('money', 10.23) // output: You have 10.23 dollars //Text widget with plural BuildContext extension Text(context.plural('money', 10.23)) //Static function with arguments var money = plural('money_args', 10.23, args: ['John', '10.23']) // output: John has 10.23 dollars //Static function with named arguments var money = plural('money_named_args', 10.23, namedArgs: {'name': 'Jane', 'money': '10.23'}) // output: Jane has 10.23 dollars var money = plural('money_named_args', 10.23, namedArgs: {'name': 'Jane'}, name: 'money') // output: Jane has 10.23 dollars ``` -------------------------------- ### Access Localization Widget Properties Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Retrieve localization configuration properties directly from the BuildContext. ```dart print(context.supportedLocales); // output: [en_US, ar_DZ, de_DE, ru_RU] print(context.fallbackLocale); // output: en_US ``` -------------------------------- ### deviceLocale Source: https://pub.dev/packages/easy_localization Retrieves the current device locale. ```APIDOC ## deviceLocale ### Description Returns the locale currently set on the device. ### Usage ```dart print(context.deviceLocale.toString()); ``` ``` -------------------------------- ### Implement legacy gender translation Source: https://pub.dev/packages/easy_localization/changelog Usage of the gender() method for translation. ```dart new Text( AppLocalizations.of(context).gender('switch', _gender ? "female" : "male"), ), ``` -------------------------------- ### Pluralization (plural) Source: https://pub.dev/packages/easy_localization Handles pluralization based on numeric values using the plural() method. ```APIDOC ## plural(key, value) ### Description Translates a key based on a numeric value for pluralization rules. ### Parameters - **value** (num) - Required - The number used for pluralization. - **args** (List) - Optional - List of strings for placeholders. - **namedArgs** (Map) - Optional - Map of strings for named placeholders. - **name** (String) - Optional - Name of the number value for {$name} replacement. - **format** (NumberFormat) - Optional - NumberFormat instance for numeric formatting. ``` -------------------------------- ### Apply Translation Arguments Source: https://pub.dev/packages/easy_localization Pass arguments to the tr() method to replace placeholders in localized strings. ```dart // args Text('msg').tr(args: ['Easy localization', 'Dart']), // namedArgs Text('msg_named').tr(namedArgs: {'lang': 'Dart'}), // args and namedArgs Text('msg_mixed').tr(args: ['Easy localization'], namedArgs: {'lang': 'Dart'}), // gender Text('gender').tr(gender: _gender ? "female" : "male"), ``` -------------------------------- ### resetLocale() Source: https://pub.dev/packages/easy_localization Resets the current application locale to the device's default locale. ```APIDOC ## resetLocale() ### Description Resets the application locale to the device locale. ### Usage ```dart context.resetLocale(); ``` ``` -------------------------------- ### Implement pluralization in Flutter Source: https://pub.dev/packages/easy_localization/changelog Usage of the plural() method with nested keys. ```dart new Text( AppLocalizations.of(context).plural("text.day", 2), ), ``` -------------------------------- ### Access generated localization keys Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Use the generated LocaleKeys class to reference translation keys as strings or widgets. ```dart print(LocaleKeys.title.tr()); //String //or Text(LocaleKeys.title).tr(); //Widget ``` -------------------------------- ### Define gender-based translations Source: https://pub.dev/packages/easy_localization/changelog JSON structure for defining male and female translation keys. ```json { "gender":{ "male": "Hi man ;)", "female": "Hello girl :)" } } ``` ```json { "gender":{ "male": "Hi man ;) {}", "female": "Hello girl :) {}" } } ``` -------------------------------- ### Translation (tr) Source: https://pub.dev/packages/easy_localization Translates language keys using the tr() method available on String, Text, or as a static function. ```APIDOC ## tr(key) ### Description Translates a given key into the current locale. ### Parameters - **args** (List) - Optional - List of strings to replace {} placeholders. - **namedArgs** (Map) - Optional - Map of strings to replace {key_name} placeholders. - **gender** (String) - Optional - Gender string to select specific translation variants. ``` -------------------------------- ### Pluralization Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Handle plural forms based on numeric values. The 'other' key is mandatory for all pluralized translations. ```json { "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" } } ``` ```dart //Text widget with format Text('money').plural(1000000, format: NumberFormat.compact(locale: context.locale.toString())) // output: You have 1M dollars //String print('day'.plural(21)); // output: 21 день //Static function var money = plural('money', 10.23) // output: You have 10.23 dollars //Text widget with plural BuildContext extension Text(context.plural('money', 10.23)) //Static function with arguments var money = plural('money_args', 10.23, args: ['John', '10.23']) // output: John has 10.23 dollars //Static function with named arguments var money = plural('money_named_args', 10.23, namedArgs: {'name': 'Jane', 'money': '10.23'}) // output: Jane has 10.23 dollars var money = plural('money_named_args', 10.23, namedArgs: {'name': 'Jane'}, name: 'money') // output: Jane has 10.23 dollars ``` -------------------------------- ### Configure Logger Levels Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Restricts logger output to specific message levels by modifying the enableLevels property. ```dart EasyLocalization.logger.enableLevels = [LevelMessages.error, LevelMessages.warning]; ``` -------------------------------- ### Format Linked Translations Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Apply modifiers like upper, lower, or capitalize to linked translation keys using the @.modifier:key syntax. ```json { ... "example": { "fullName": "Full Name", "emptyNameError": "Please fill in your @.lower:example.fullName" } ... } ``` ```dart print('example.emptyNameError'.tr()); //Output: Please fill in your full name ``` -------------------------------- ### Reset Locale Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Revert the application locale to the device's current locale. ```dart RaisedButton( onPressed: (){ context.resetLocale(); }, child: Text(LocaleKeys.reset_locale).tr(), ) ``` -------------------------------- ### Convert Locale to String Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Converts a Locale object into a string using a specified separator. ```dart Locale('en', 'US').toStringWithSeparator(separator: '|') // en|US ``` -------------------------------- ### Implement gender translation in Flutter Source: https://pub.dev/packages/easy_localization/changelog Usage of tr() with gender parameters in a Text widget. ```dart new Text( AppLocalizations.of(context).tr('switch', gender: _gender ? "female" : "male"), ), ``` ```dart new Text( AppLocalizations.of(context).tr('switch', args:["Naama"] gender: _gender ? "female" : "male"), ), ``` -------------------------------- ### Disable Logger Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Disables all logging by setting the enableBuildModes property to an empty list. ```dart EasyLocalization.logger.enableBuildModes = []; ``` -------------------------------- ### Override Logger Printer Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Defines a custom printer function to intercept and handle log messages. ```dart EasyLogPrinter customLogPrinter = ( Object object, { String name, StackTrace stackTrace, LevelMessages level, }) { ///Your function print('$name: ${object.toString()}'); }; /// override printer to custom EasyLocalization.logger.printer = customLogPrinter; ``` -------------------------------- ### Convert String to Locale Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Converts a string representation of a locale into a Locale object, optionally specifying a custom separator. ```dart 'en_US'.toLocale(); // Locale('en', 'US') //with custom separator 'en|US'.toLocale(separator: '|') // Locale('en', 'US') ``` -------------------------------- ### deleteSaveLocale() Source: https://pub.dev/packages/easy_localization Clears the saved locale from the device storage. ```APIDOC ## deleteSaveLocale() ### Description Removes any previously saved locale preference from the device storage. ### Usage ```dart context.deleteSaveLocale(); ``` ``` -------------------------------- ### Delete Saved Locale Source: https://pub.dev/packages/easy_localization/versions/3.0.8 Remove the persisted locale from device storage. ```dart RaisedButton( onPressed: (){ context.deleteSaveLocale(); }, child: Text(LocaleKeys.reset_locale).tr(), ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.