### Installation Rules for Runtime Bundle Source: https://github.com/aissat/easy_localization/blob/develop/example/linux/CMakeLists.txt Defines installation rules for creating a relocatable runtime bundle. It includes cleaning the bundle directory, installing the executable, ICU data, Flutter library, and bundled plugin libraries. ```cmake set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Example Translation File (en-US.json) Source: https://context7.com/aissat/easy_localization/llms.txt An example JSON file for English (US) translations, demonstrating various translation types including placeholders, named arguments, gender, plurals, and nested keys. ```json { "title": "Hello", "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 {}" }, "clicked": { "zero": "You haven't clicked yet!", "one": "You clicked {} time!", "other": "You clicked {} times!" }, "amount": { "zero": "Your amount: {}", "one": "Your amount: {}", "other": "Your amount: {}" }, "profile": { "reset_password": { "label": "Reset Password", "username": "Username" } }, "reset_locale": "Reset Language" } ``` -------------------------------- ### Install Flutter Assets Source: https://github.com/aissat/easy_localization/blob/develop/example/linux/CMakeLists.txt Installs the Flutter assets directory into the runtime bundle. It ensures assets are up-to-date by removing the old directory before copying new files. ```cmake set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Linked Translations Example Source: https://github.com/aissat/easy_localization/blob/develop/README.md Shows how to link translation keys using the '@:' prefix to reuse existing translations. This example demonstrates linking simple strings and nested arguments. ```json { ... "example": { "hello": "Hello", "world": "World!", "helloWorld": "@:example.hello @:example.world" } ... } ``` ```dart print('example.helloWorld'.tr()); //Output: Hello World! ``` ```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. ``` -------------------------------- ### Install EasyLogger Source: https://github.com/aissat/easy_localization/blob/develop/packages/easy_logger/README.md Add the EasyLogger dependency to your pubspec.yaml file to include it in your project. ```yaml dependencies: easy_logger: ``` -------------------------------- ### Pluralization Examples with Easy Localization Source: https://github.com/aissat/easy_localization/blob/develop/README.md Demonstrates various ways to use the pluralization functionality with different argument types and contexts. Includes usage with Text widgets, static functions, and BuildContext extensions. ```dart Text('money').plural(1000000, format: NumberFormat.compact(locale: context.locale.toString())) ``` ```dart print('day'.plural(21)); ``` ```dart var money = plural('money', 10.23) ``` ```dart Text(context.plural('money', 10.23)) ``` ```dart var money = plural('money_args', 10.23, args: ['John', '10.23']) ``` ```dart var money = plural('money_named_args', 10.23, namedArgs: {'name': 'Jane', 'money': '10.23'}) ``` ```dart var money = plural('money_named_args', 10.23, namedArgs: {'name': 'Jane'}, name: 'money') ``` -------------------------------- ### EasyLocalization Widget Setup Source: https://context7.com/aissat/easy_localization/llms.txt The root widget that provides localization state to the subtree. It must wrap the app widget and requires supported locales and a path to translation files. ```dart EasyLocalization( // Required supportedLocales: [Locale('en', 'US'), Locale('de', 'DE'), Locale('ar', 'DZ')], path: 'assets/translations', child: MyApp(), // Optional fallbackLocale: Locale('en', 'US'), // used when device locale is not in supportedLocales startLocale: Locale('de', 'DE'), // override device locale at startup saveLocale: true, // persist chosen locale via shared_preferences (default: true) useOnlyLangCode: false, // 'en.json' vs 'en-US.json' (default: false) useFallbackTranslations: true, // fall back to fallbackLocale for missing keys useFallbackTranslationsForEmptyResources: true, // also fall back for empty string values ignorePluralRules: false, // false = full ICU rules (few/many); true = simplified (default: true) assetLoader: RootBundleAssetLoader( fileLoader: RootBundleFileLoader(), linkedFileResolver: JsonLinkedFileResolver(fileLoader: RootBundleFileLoader()), ), extraAssetLoaders: [ // loaders for packages/modules with their own translations TranslationsLoader(packageName: 'my_package'), ], errorWidget: (error) => MyErrorPage(error), // custom widget shown when translations fail to load ) ``` -------------------------------- ### Install AOT Library Conditionally Source: https://github.com/aissat/easy_localization/blob/develop/example/linux/CMakeLists.txt Installs the Ahead-Of-Time (AOT) compiled library on non-Debug builds. This optimizes performance for release configurations. ```cmake if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Configure EasyLocalization with Extra Asset Loaders Source: https://github.com/aissat/easy_localization/blob/develop/README.md Add localization support from other modules or packages by specifying them in `extraAssetLoaders` during EasyLocalization setup. ```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'), ], )); } ``` -------------------------------- ### EasyLocalization.ensureInitialized() Source: https://context7.com/aissat/easy_localization/llms.txt A static asynchronous method that must be called before `runApp`. This ensures that the saved locale from device storage is pre-loaded, allowing the app to start immediately in the correct locale. ```APIDOC ## `EasyLocalization.ensureInitialized()` Static async method that must be called before `runApp` to pre-load the saved locale from device storage so the app starts in the correct locale immediately. ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); await EasyLocalization.ensureInitialized(); runApp( EasyLocalization( supportedLocales: [Locale('en', 'US'), Locale('fr', 'FR')], path: 'assets/translations', child: MyApp(), ), ); } ``` ``` -------------------------------- ### Initialize EasyLocalization Before runApp Source: https://context7.com/aissat/easy_localization/llms.txt Call `EasyLocalization.ensureInitialized()` before `runApp` to pre-load the saved locale from device storage, ensuring the app starts in the correct locale immediately. ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); await EasyLocalization.ensureInitialized(); runApp( EasyLocalization( supportedLocales: [Locale('en', 'US'), Locale('fr', 'FR')], path: 'assets/translations', child: MyApp(), ), ); } ``` -------------------------------- ### Set Minimum CMake Version and Project Name Source: https://github.com/aissat/easy_localization/blob/develop/example/linux/CMakeLists.txt Specifies the minimum required CMake version and names the project. This is a standard starting point for any CMake project. ```cmake cmake_minimum_required(VERSION 3.10) project(runner LANGUAGES CXX) ``` -------------------------------- ### Get Easy Localization Widget Properties Source: https://github.com/aissat/easy_localization/blob/develop/README.md Access properties like supportedLocales, fallbackLocale, and localizationDelegates from the Easy Localization widget using BuildContext. This allows you to inspect the current localization setup. ```dart print(context.supportedLocales); // output: [en_US, ar_DZ, de_DE, ru_RU] print(context.fallbackLocale); // output: en_US ``` -------------------------------- ### Pluralization Example Source: https://github.com/aissat/easy_localization/blob/develop/README.md Translate strings with pluralization support. Use `{}` to insert numbers, which can be formatted using `NumberFormat`. This can be done via string extensions or static functions. ```dart // Example usage for pluralization would go here, similar to tr() examples. ``` -------------------------------- ### EasyLocalization Widget Source: https://context7.com/aissat/easy_localization/llms.txt The root widget that provides localization state to the subtree. It must wrap the main app widget and requires `supportedLocales` and `path` for translation files. Optional parameters allow for fallback locales, starting locales, persistence, and custom asset loaders. ```APIDOC ## EasyLocalization Widget The root widget that provides localization state to the subtree; must wrap the app widget. ```dart EasyLocalization( // Required supportedLocales: [Locale('en', 'US'), Locale('de', 'DE'), Locale('ar', 'DZ')], path: 'assets/translations', child: MyApp(), // Optional fallbackLocale: Locale('en', 'US'), // used when device locale is not in supportedLocales startLocale: Locale('de', 'DE'), // override device locale at startup saveLocale: true, // persist chosen locale via shared_preferences (default: true) useOnlyLangCode: false, // 'en.json' vs 'en-US.json' (default: false) useFallbackTranslations: true, // fall back to fallbackLocale for missing keys useFallbackTranslationsForEmptyResources: true, // also fall back for empty string values ignorePluralRules: false, // false = full ICU rules (few/many); true = simplified (default: true) assetLoader: RootBundleAssetLoader( fileLoader: RootBundleFileLoader(), linkedFileResolver: JsonLinkedFileResolver(fileLoader: RootBundleFileLoader()), ), extraAssetLoaders: [ TranslationsLoader(packageName: 'my_package'), ], errorWidget: (error) => MyErrorPage(error), ) ``` ``` -------------------------------- ### Import Generated Locale Keys Source: https://github.com/aissat/easy_localization/blob/develop/README.md After generating the locale keys file, import it into your Dart code to start using the generated keys. ```dart import 'generated/locale_keys.g.dart'; ``` -------------------------------- ### JSON Structure for Pluralization Source: https://github.com/aissat/easy_localization/blob/develop/README.md Example JSON structure defining pluralization rules for different categories (zero, one, two, few, many, other) and argument types (direct, with args, with namedArgs). ```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" } } ``` -------------------------------- ### Translate Linked Messages Source: https://github.com/aissat/easy_localization/blob/develop/README.md Translate messages that reference other keys, applying formatting modifiers. The example shows how to output a lowercase version of a linked message. ```dart print('example.emptyNameError'.tr()); //Output: Please fill in your full name ``` -------------------------------- ### Change or Get Locale using Context Extensions Source: https://github.com/aissat/easy_localization/blob/develop/README.md Use extension methods on `BuildContext` to easily change or retrieve the current locale. The older static method `EasyLocalization.of(context)` is still supported. ```dart context.setLocale(Locale('en', 'US')); print(context.locale.toString()); ``` -------------------------------- ### Configure Global EasyLogger Instance Source: https://github.com/aissat/easy_localization/blob/develop/packages/easy_logger/README.md Create a global instance of EasyLogger with custom configurations for name prefix, default log level, enabled build modes, and enabled log levels. ```dart import 'package:easy_logger/easy_logger.dart'; final EasyLogger logger = EasyLogger( name: 'NamePrefix', defaultLevel: LevelMessages.debug, enableBuildModes: [BuildMode.debug, BuildMode.profile, BuildMode.release], enableLevels: [LevelMessages.debug, LevelMessages.info, LevelMessages.error, LevelMessages.warning], ); void main() async { ... ``` -------------------------------- ### Configuring Plural Rules in Easy Localization Source: https://github.com/aissat/easy_localization/blob/develop/README.md Demonstrates how to initialize EasyLocalization with the `ignorePluralRules` flag set to `false` to enable handling of 'few' and 'many' plural categories for specific languages. ```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() ) ``` -------------------------------- ### Find and check system libraries for Flutter Source: https://github.com/aissat/easy_localization/blob/develop/example/linux/flutter/CMakeLists.txt Uses PkgConfig to find and check for required system-level libraries such as GTK, GLIB, GIO, BLKID, and LZMA. These are essential for the Flutter Linux embedding. ```cmake find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) pkg_check_modules(BLKID REQUIRED IMPORTED_TARGET blkid) pkg_check_modules(LZMA REQUIRED IMPORTED_TARGET liblzma) ``` -------------------------------- ### Get Device Locale Source: https://github.com/aissat/easy_localization/blob/develop/README.md Retrieve the device's current locale using the deviceLocale property. The output is a string representation of the locale, e.g., 'en_US'. ```dart print(context.deviceLocale.toString()) // OUTPUT: en_US ``` -------------------------------- ### Define Application Executable and Link Libraries Source: https://github.com/aissat/easy_localization/blob/develop/example/linux/CMakeLists.txt Defines the main executable target and links necessary libraries, including Flutter, GTK, and generated plugin code. It also applies standard compilation settings. ```cmake add_executable(${BINARY_NAME} "main.cc" "my_application.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) apply_standard_settings(${BINARY_NAME}) target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) add_dependencies(${BINARY_NAME} flutter_assemble) ``` -------------------------------- ### Generate LocaleKeys with easy_localization CLI Source: https://context7.com/aissat/easy_localization/llms.txt Use this command to generate type-safe locale keys from your translation files. Specify input and output paths, and choose the output format. ```bash flutter pub run easy_localization:generate \ -S assets/translations \ -O lib/generated \ -o locale_keys.g.dart \ -f keys \ -u # --skip-unnecessary-keys: omit intermediate nested object keys ``` -------------------------------- ### Add Dependency and Asset Paths to pubspec.yaml Source: https://context7.com/aissat/easy_localization/llms.txt Declare the easy_localization dependency and specify the path for translation assets in your pubspec.yaml file. ```yaml # pubspec.yaml dependencies: easy_localization: ^3.0.9 flutter: assets: - assets/translations/ ``` -------------------------------- ### Generate Localization Keys with Easy Localization Source: https://github.com/aissat/easy_localization/blob/develop/README.md Run this command in your terminal to generate a locale keys file. This helps in managing and auto-prompting localization keys in your code editor. Ensure you have the `codegen_loader` dependency if using `CodegenLoader`. ```bash flutter pub run easy_localization:generate -f keys -o locale_keys.g.dart ``` -------------------------------- ### Log Messages Using Helper Methods Source: https://github.com/aissat/easy_localization/blob/develop/packages/easy_logger/README.md Utilize helper methods for common log levels (debug, info, warning, error) for more concise logging calls. ```dart logger.debug('your log text'); logger.info('your log text'); logger.warning('your log text'); logger.error('your log text'); ``` -------------------------------- ### Configure MaterialApp for EasyLocalization Source: https://github.com/aissat/easy_localization/blob/develop/example/README.md Set up MaterialApp to use EasyLocalization's delegates and locale settings. This ensures that translations are applied correctly throughout the application. ```dart return MaterialApp( title: 'Flutter Demo', localizationsDelegates: [ GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, EasyLocalization.of(context).delegate, ], supportedLocales: EasyLocalization.of(context).supportedLocales, locale: EasyLocalization.of(context).locale, theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Easy localization'), ); ``` -------------------------------- ### Log with StackTrace Source: https://github.com/aissat/easy_localization/blob/develop/packages/easy_logger/README.md Capture and log an exception along with its stack trace for detailed error analysis. ```dart try { //same code } on Exception catch (e, stackTrace) { logger('same error', stackTrace: stackTrace); } ``` -------------------------------- ### Initialize EasyLocalization Source: https://github.com/aissat/easy_localization/blob/develop/example/README.md Ensure EasyLocalization is initialized before running the app. Configure supported locales, the path to translation files, and optionally an asset loader. ```dart void main() async{ // WidgetsFlutterBinding.ensureInitialized(); await EasyLocalization.ensureInitialized(); runApp(EasyLocalization( child: MyApp(), supportedLocales: [Locale('en', 'US'), Locale('ar', 'DZ')], path: 'resources/langs', // fallbackLocale: Locale('en', 'US'), // saveLocale: false, // useOnlyLangCode: true, // 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() )); } ``` -------------------------------- ### Set Runtime Output Directory Source: https://github.com/aissat/easy_localization/blob/develop/example/linux/CMakeLists.txt Configures the runtime output directory for the executable to a subdirectory. This is to prevent users from running the unbundled copy, ensuring resources are correctly located. ```cmake set_target_properties(${BINARY_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" ) ``` -------------------------------- ### Initialize EasyLocalization Source: https://github.com/aissat/easy_localization/blob/develop/README.md Call `EasyLocalization.ensureInitialized()` in your main function before `runApp`. Ensure `WidgetsFlutterBinding.ensureInitialized()` is also called. ```dart void main() async{ // ... // Needs to be called so that we can await for EasyLocalization.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized(); await EasyLocalization.ensureInitialized(); // ... runApp(....) // ... } ``` -------------------------------- ### Linked Translation Files Source: https://context7.com/aissat/easy_localization/llms.txt Shows how to split locale translations across multiple JSON files using the ':/filename.json' syntax for better maintainability. ```json // assets/translations/en-US.json (root file) // { // "auth": ":/auth.json", // "errors": ":/errors.json" // } // // assets/translations/en-US/auth.json // { "login": "Sign In", "logout": "Sign Out" } // // assets/translations/en-US/errors.json // { "network": "No internet connection", "timeout": "Request timed out" } ``` ```yaml // pubspec.yaml — declare the subfolder too: // flutter: // assets: // - assets/translations/ // - assets/translations/en-US/ ``` ```dart // Usage is identical to a flat structure: Text('auth.login').tr() // → "Sign In" Text('errors.network').tr() // → "No internet connection" ``` -------------------------------- ### Configure Asset Loader with CodegenLoader Source: https://github.com/aissat/easy_localization/blob/develop/README.md Integrate the generated CodegenLoader by importing it and setting it as the assetLoader in the EasyLocalization widget. This step is crucial after running the code generation command. ```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() )); } ... ``` -------------------------------- ### Declare Translation Assets Source: https://github.com/aissat/easy_localization/blob/develop/README.md Specify the directory containing your translation files in the pubspec.yaml file. ```yaml flutter: assets: - assets/translations/ ``` -------------------------------- ### Configure Flutter library and headers Source: https://github.com/aissat/easy_localization/blob/develop/example/linux/flutter/CMakeLists.txt Sets variables for the Flutter library path and ICU data file, and defines a list of Flutter library headers. These are then used to configure an interface library for Flutter. ```cmake set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) list(APPEND FLUTTER_LIBRARY_HEADERS "fl_basic_message_channel.h" "fl_binary_codec.h" "fl_binary_messenger.h" "fl_dart_project.h" "fl_engine.h" "fl_json_message_codec.h" "fl_json_method_codec.h" "fl_message_codec.h" "fl_method_call.h" "fl_method_channel.h" "fl_method_codec.h" "fl_method_response.h" "fl_plugin_registrar.h" "fl_plugin_registry.h" "fl_standard_message_codec.h" "fl_standard_method_codec.h" "fl_string_codec.h" "fl_value.h" "fl_view.h" "flutter_linux.h" ) list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") ``` -------------------------------- ### Create Flutter interface library Source: https://github.com/aissat/easy_localization/blob/develop/example/linux/flutter/CMakeLists.txt Defines an interface library named 'flutter' and configures its include directories and linked libraries. This includes the Flutter library itself and the system libraries found earlier. ```cmake add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") target_link_libraries(flutter INTERFACE PkgConfig::GTK PkgConfig::GLIB PkgConfig::GIO PkgConfig::BLKID PkgConfig::LZMA ) ``` -------------------------------- ### `BuildContext` Locale Extensions Source: https://context7.com/aissat/easy_localization/llms.txt Extension methods on `BuildContext` to read and mutate the active locale, reset to the device locale, clear the persisted locale, and access widget configuration. ```APIDOC ## `BuildContext` Locale Extensions Extension methods on `BuildContext` to read and mutate the active locale, reset to the device locale, clear the persisted locale, and access widget configuration. ### Methods: **Get current locale:** ```dart Locale current = context.locale; // → Locale('en', 'US') print(current.toString()); // → "en_US" ``` **Change locale (must be in supportedLocales):** ```dart await context.setLocale(Locale('de', 'DE')); // Locale is saved to device storage automatically (if saveLocale: true) ``` **Get device/platform locale:** ```dart print(context.deviceLocale.toString()); // → "en_US" ``` **Get previously saved locale (null if never saved):** ```dart print(context.savedLocale); // → Locale('de', 'DE') or null ``` **Reset to device locale (also clears saved locale):** ```dart ElevatedButton( onPressed: () => context.resetLocale(), child: Text('reset_locale').tr(), ) ``` **Delete saved locale from storage (next app start uses device locale):** ```dart await context.deleteSaveLocale(); ``` **Access widget configuration:** ```dart print(context.supportedLocales); // → [Locale('en', 'US'), Locale('de', 'DE'), Locale('ar', 'DZ')] print(context.fallbackLocale); // → Locale('en', 'US') List delegates = context.localizationDelegates; // Pass to MaterialApp.localizationsDelegates — includes GlobalMaterialLocalizations etc. ``` ``` -------------------------------- ### Custom HttpAssetLoader Implementation Source: https://context7.com/aissat/easy_localization/llms.txt Extends AssetLoader to load translation data from an HTTP source. Requires specifying the base URL for translations. ```dart import 'dart:convert'; import 'dart:ui'; import 'package:easy_localization/easy_localization.dart'; import 'package:http/http.dart' as http; class HttpAssetLoader extends AssetLoader { final String baseUrl; const HttpAssetLoader({ required this.baseUrl, required super.fileLoader, required super.linkedFileResolver, }); @override Future?> load(String path, Locale locale) async { final url = '$baseUrl/${locale.toStringWithSeparator(separator: '-')}.json'; final response = await http.get(Uri.parse(url)); if (response.statusCode == 200) { return json.decode(response.body) as Map; } return null; } } ``` ```dart // Use in EasyLocalization: EasyLocalization( supportedLocales: [Locale('en', 'US'), Locale('fr', 'FR')], path: 'https://cdn.example.com/translations', // passed as `path` to load() assetLoader: HttpAssetLoader( baseUrl: 'https://cdn.example.com/translations', fileLoader: RootBundleFileLoader(), linkedFileResolver: JsonLinkedFileResolver(fileLoader: RootBundleFileLoader()), ), child: MyApp(), ) ``` -------------------------------- ### Configure Build Options Source: https://github.com/aissat/easy_localization/blob/develop/example/linux/CMakeLists.txt Sets the default build type to 'Debug' if not already specified. This ensures a consistent build mode for development. ```cmake if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() ``` -------------------------------- ### Configure Easy Localization Widget Source: https://github.com/aissat/easy_localization/blob/develop/README.md Add the EasyLocalization widget to your main application file. Ensure EasyLocalization.ensureInitialized() is called before runApp(). Configure supported locales, translation path, and fallback locale. ```dart import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:easy_localization/easy_localization.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await EasyLocalization.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() ), ); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( localizationsDelegates: context.localizationDelegates, supportedLocales: context.supportedLocales, locale: context.locale, home: MyHomePage() ); } } ``` -------------------------------- ### Audit Missing Translation Keys with easy_localization CLI Source: https://context7.com/aissat/easy_localization/llms.txt Run this command to scan your Dart source for translation keys used with `.tr()` or `.plural()` that are missing from your translation files. Helps catch missing translations before deployment. ```bash # Default paths (assets/translations + lib/): flutter pub run easy_localization:audit # Custom paths: flutter pub run easy_localization:audit \ -t resources/langs \ -s src/dart # Example output: # ✗ Missing key: 'onboarding.step1' (found in lib/screens/onboarding.dart:42) # ✗ Missing key: 'errors.payment' (found in lib/services/payment.dart:87) # ✓ All other keys are present. ``` -------------------------------- ### Link External Translation Files Source: https://github.com/aissat/easy_localization/blob/develop/README.md Split translations into multiple files by prefixing the value with ':/' followed by the filename. Ensure linked files are in the translations directory. ```json { "errors": ":/errors.json", "validation": ":/validation.json", "notifications": ":/notifications.json" } ``` -------------------------------- ### Apply Standard Compilation Settings Function Source: https://github.com/aissat/easy_localization/blob/develop/example/linux/CMakeLists.txt Defines a function to apply common compilation features and options to targets. It enables C++14, sets warning levels, and applies optimization flags based on the build configuration. ```cmake function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_14) target_compile_options(${TARGET} PRIVATE -Wall -Werror) target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") endfunction() ``` -------------------------------- ### Generate Localization Code Source: https://github.com/aissat/easy_localization/blob/develop/README.md Run the 'flutter pub run easy_localization:generate' command in your terminal to generate localization code. Use command-line arguments to customize the source and output directories, file names, and formats. ```bash flutter pub run easy_localization:generate -h ``` -------------------------------- ### Code Generation Command Source: https://context7.com/aissat/easy_localization/llms.txt Command to generate a CodegenLoader and LocaleKeys class, embedding translations directly in Dart and providing typed key constants. ```bash # Generate CodegenLoader (embeds JSON in Dart): flutter pub run easy_localization:generate \ -S assets/translations \ -O lib/generated \ -o codegen_loader.g.dart \ -f json ``` -------------------------------- ### Add easy_localization Dependency Source: https://github.com/aissat/easy_localization/blob/develop/README.md Add the easy_localization package to your pubspec.yaml file to include it in your project. ```yaml dependencies: easy_localization: ``` -------------------------------- ### Initialize Easy Localization in main.dart Source: https://context7.com/aissat/easy_localization/llms.txt Initialize Easy Localization before running the app by calling `EasyLocalization.ensureInitialized()`. This loads the saved locale from storage. Configure supported locales, asset path, and fallback locale. ```dart import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:easy_localization/easy_localization.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await EasyLocalization.ensureInitialized(); // loads saved locale from storage runApp( EasyLocalization( supportedLocales: [ Locale('en', 'US'), Locale('de', 'DE'), Locale('ar', 'DZ'), ], path: 'assets/translations', fallbackLocale: Locale('en', 'US'), // startLocale: Locale('de', 'DE'), // override device locale // saveLocale: false, // disable locale persistence // useOnlyLangCode: true, // load "en.json" instead of "en-US.json" // useFallbackTranslations: true, // use fallbackLocale for missing keys // ignorePluralRules: false, // enable full ICU plural rules (few/many) child: MyApp(), ), ); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( localizationsDelegates: context.localizationDelegates, // includes GlobalMaterialLocalizations etc. supportedLocales: context.supportedLocales, locale: context.locale, home: MyHomePage(), ); } } ``` -------------------------------- ### Audit Missing Translation Keys Source: https://github.com/aissat/easy_localization/blob/develop/README.md Run this command to audit your translation keys. It identifies keys present in your app code but missing from your translation files, helping to ensure all translations are accounted for. ```bash flutter pub run easy_localization:audit ``` -------------------------------- ### Simple Logger Usage Source: https://github.com/aissat/easy_localization/blob/develop/packages/easy_logger/README.md Log a simple message using the global logger instance. This will use the default log level. ```dart logger('Your log text'); ``` -------------------------------- ### `trExists()` — Key Existence Check Source: https://context7.com/aissat/easy_localization/llms.txt Returns `true` if the given localization key exists in the currently loaded translations. Available as a static function, a `String` extension, and a `BuildContext` extension. ```APIDOC ## `trExists()` — Key Existence Check Returns `true` if the given localization key exists in the currently loaded translations; available as a static function, a `String` extension, and a `BuildContext` extension. ### Usage Examples: **Conditional rendering:** ```dart if ('beta.newFeature'.trExists()) { Text('beta.newFeature').tr(); } else { Text('Coming soon'); } ``` **String extension:** ```dart bool hasKey = 'title'.trExists(); // → true bool missing = 'nonexistent.key'.trExists(); // → false ``` **BuildContext extension (throws LocalizationNotFoundException if EasyLocalization not in tree):** ```dart bool exists = context.trExists('profile.reset_password.label'); // → true ``` **Static function with optional context:** ```dart bool check = trExists('gender', context: context); ``` ``` -------------------------------- ### Define list_prepend function for CMake < 3.10 Source: https://github.com/aissat/easy_localization/blob/develop/example/linux/flutter/CMakeLists.txt Defines a custom CMake function 'list_prepend' to add a prefix to each element of a list. This is a workaround for versions of CMake older than 3.10, which do not support the 'list(TRANSFORM ... PREPEND ...)' command. ```cmake function(list_prepend LIST_NAME PREFIX) set(NEW_LIST "") foreach(element ${${LIST_NAME}}) list(APPEND NEW_LIST "${PREFIX}${element}") endforeach(element) set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) endfunction() ``` -------------------------------- ### English (US) Localization JSON Source: https://github.com/aissat/easy_localization/blob/develop/example/README.md This JSON file provides English translations for an application. It covers greetings, messages, profile settings, click counters, and gendered responses. ```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!", "two":"You clicked {} times!", "few":"You clicked {} times!", "many":"You clicked {} times!", "other": "You clicked {} times!" }, "gender":{ "male": "Hi man ;) ", "female": "Hello girl :)", "with_arg":{ "male": "Hi man ;) {}", "female": "Hello girl :) {}" } } } ``` -------------------------------- ### Integrating Multi-Package Translations Source: https://context7.com/aissat/easy_localization/llms.txt Provide additional `AssetLoader` instances via `extraAssetLoaders` to load translations from multiple packages. Each loader is responsible for its own package's translation files. ```dart runApp(EasyLocalization( supportedLocales: [Locale('en', 'US'), Locale('de', 'DE')], path: 'assets/translations', assetLoader: CodegenLoader(), extraAssetLoaders: [ TranslationsLoader(packageName: 'package_a'), TranslationsLoader(packageName: 'package_b'), ], fallbackLocale: Locale('en', 'US'), child: MyApp(), )); // All keys from all loaders are merged and usable identically: Text('package_a.greeting').tr() // → "Hello from Package A" Text('package_b.info').tr() // → "Package B info" ``` -------------------------------- ### Initialize Easy Localization in Flutter App Source: https://context7.com/aissat/easy_localization/llms.txt Set up Easy Localization in your Flutter application's main function. Ensure Easy Localization is initialized before running the app and configure supported locales, path, and asset loader. ```dart import 'package:easy_localization/easy_localization.dart'; import 'generated/codegen_loader.g.dart'; import 'generated/locale_keys.g.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await EasyLocalization.ensureInitialized(); runApp(EasyLocalization( supportedLocales: [Locale('en', 'US'), Locale('ar', 'DZ')], path: 'assets/translations', assetLoader: CodegenLoader(), // no async file I/O — translations embedded in Dart child: MyApp(), )); } ``` -------------------------------- ### Build Language Selection UI in Flutter Source: https://github.com/aissat/easy_localization/blob/develop/example/README.md This widget builds a UI for selecting languages. It uses `easy_localization` to manage locale changes. Ensure the `easy_localization` package is imported. ```dart import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:easy_localization/easy_localization.dart'; class LanguageView extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( "", style: TextStyle(color: Colors.black), ), backgroundColor: Colors.white, iconTheme: IconThemeData(color: Colors.black), elevation: 0, ), body: Container( color: Colors.white, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( padding: EdgeInsets.only(top: 26), margin: EdgeInsets.symmetric( horizontal: 24, ), child: Text( "Language Menu", style: TextStyle( color: Color.fromARGB(255, 166, 166, 166), fontFamily: "Montserrat", fontWeight: FontWeight.w700, fontSize: 10, ), ), ), Container( padding: EdgeInsets.only(top: 10, bottom: 25), margin: EdgeInsets.symmetric( horizontal: 24, ), child: Text( "language", ), ), buildDivider(), buildSwitchListTileMenuItem( context: context, title: "عربي", subtitle: "عربي", locale: Locale("ar", "DZ")), buildDivider(), buildSwitchListTileMenuItem( context: context, title: "English", subtitle: "English", locale: Locale("en", "US")), buildDivider(), ], ), ), ); } Container buildDivider() => Container( margin: EdgeInsets.symmetric( horizontal: 24, ), child: Divider( color: Colors.grey, ), ); Container buildSwitchListTileMenuItem( {BuildContext context, String title, String subtitle, Locale locale}) { return Container( margin: EdgeInsets.only( left: 10, right: 10, top: 5, ), child: ListTile( dense: true, // isThreeLine: true, title: Text( title, ), subtitle: Text( subtitle, ), onTap: () { log(locale.toString(), name: this.toString()); EasyLocalization.of(context).locale = locale; }), ); } } ``` -------------------------------- ### Translate with Arguments Source: https://github.com/aissat/easy_localization/blob/develop/README.md Translate localization keys using arguments for placeholders. Supports positional arguments (`args`), named arguments (`namedArgs`), and gender-specific translations. ```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"), ``` -------------------------------- ### Custom command to build Flutter library Source: https://github.com/aissat/easy_localization/blob/develop/example/linux/flutter/CMakeLists.txt Defines a custom CMake command to build the Flutter library and headers using the Flutter tool backend. This command is triggered when the output files are missing or outdated. ```cmake add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CMAKE_CURRENT_BINARY_DIR}/_phony_ COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" linux-x64 ${CMAKE_BUILD_TYPE} VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ) ``` -------------------------------- ### Redirect Logger Output Source: https://context7.com/aissat/easy_localization/llms.txt Configure the logger to capture messages and redirect them to an external logging system like Firebase Crashlytics or Sentry. Includes a fallback to `debugPrint`. ```dart // Capture log messages (e.g., send to Crashlytics/Sentry): EasyLocalization.logger.printer = ( Object message, { String? name, StackTrace? stackTrace, LevelMessages? level, }) { if (level == LevelMessages.error || level == LevelMessages.warning) { FirebaseCrashlytics.instance.log('[$name] $message'); } // Fallback: also print to console debugPrint('$name: $message'); }; ``` -------------------------------- ### Translate Text using String Extension Source: https://github.com/aissat/easy_localization/blob/develop/README.md Use the `.tr()` extension method on strings for translation. This is recommended for `Text` widgets as it handles rebuilds on locale change. ```dart Text('title').tr() //Text widget ``` -------------------------------- ### BuildContext Locale Extensions Source: https://context7.com/aissat/easy_localization/llms.txt Provides extension methods on BuildContext for managing the active locale. Allows reading the current, device, and saved locales, changing the locale, resetting to the device locale, and clearing saved locales. ```dart // Get current locale Locale current = context.locale; // → Locale('en', 'US') print(current.toString()); // → "en_US" // Change locale (must be in supportedLocales) await context.setLocale(Locale('de', 'DE')); // Locale is saved to device storage automatically (if saveLocale: true) // Get device/platform locale print(context.deviceLocale.toString()); // → "en_US" // Get previously saved locale (null if never saved) print(context.savedLocale); // → Locale('de', 'DE') or null // Reset to device locale (also clears saved locale) ElevatedButton( onPressed: () => context.resetLocale(), child: Text('reset_locale').tr(), ) // Delete saved locale from storage (next app start uses device locale) await context.deleteSaveLocale(); // Access widget configuration print(context.supportedLocales); // → [Locale('en', 'US'), Locale('de', 'DE'), Locale('ar', 'DZ')] print(context.fallbackLocale); // → Locale('en', 'US') List delegates = context.localizationDelegates; // Pass to MaterialApp.localizationsDelegates — includes GlobalMaterialLocalizations etc. ``` -------------------------------- ### Arabic (Algeria) Localization JSON Source: https://github.com/aissat/easy_localization/blob/develop/example/README.md This JSON file contains translations for an application in Algerian Arabic. It includes general messages, profile-related fields, click counts, and gender-specific greetings. ```json { "title": "السلام", "msg":"السلام عليكم يا {} في عالم {}", "clickMe":"إضغط هنا", "profile": { "reset_password": { "label": "اعادة تعين كلمة السر", "username": "المستخدم", "password": "كلمة السر" } }, "clicked": { "zero": "{} نقرة!", "one": "{} نقرة!", "two":"{} نقرات!", "few":"{} نقرات!", "many":"{} نقرة!", "other": "{} نقرة!" }, "gender":{ "male": " مرحبا يا رجل", "female": " مرحبا بك يا فتاة", "with_arg":{ "male": "{} مرحبا يا رجل", "female": "{} مرحبا بك يا فتاة" } } } ``` -------------------------------- ### Configure Easy Localization Logger Levels Source: https://context7.com/aissat/easy_localization/llms.txt Customize the logger to control which message levels (error, warning, info, debug) are displayed. This is useful for debugging or reducing log verbosity in production. ```dart import 'package:easy_localization/easy_localization.dart'; import 'package:easy_logger/easy_logger.dart'; // Show only warnings and errors (hides debug/info messages): EasyLocalization.logger.enableLevels = [LevelMessages.error, LevelMessages.warning]; // Disable logger entirely (e.g., in production release builds): EasyLocalization.logger.enableBuildModes = []; ``` -------------------------------- ### Translate Text using Context Extension Source: https://github.com/aissat/easy_localization/blob/develop/README.md Use the `context.tr()` extension method on `Text` widgets to translate localization keys. This ensures the widget rebuilds when the locale changes. ```dart Text(context.tr('title')) ``` -------------------------------- ### Use Generated Localization Keys Source: https://github.com/aissat/easy_localization/blob/develop/README.md Access and use the generated localization keys for translating strings or displaying translated text in widgets. The `.tr()` extension method is used for translation. ```dart print(LocaleKeys.title.tr()); //String //or Text(LocaleKeys.title).tr(); //Widget ``` -------------------------------- ### Define Custom Log Printer Function Source: https://github.com/aissat/easy_localization/blob/develop/packages/easy_logger/README.md Create a custom function to handle the printing of log messages, allowing for unique formatting or output destinations. ```dart EasyLogPrinter customLogPrinter = ( Object object, { String name, StackTrace stackTrace, LevelMessages level, } ) { print('$name: ${object.toString()}'); }; final EasyLogger logger = EasyLogger( printer: customLogPrinter, ); ``` -------------------------------- ### Pluralization with EasyLocalization Source: https://github.com/aissat/easy_localization/blob/develop/example/README.md Handle pluralization of strings based on a counter. The `.plural()` method or `plural()` function can be used to select the correct plural form. ```dart Text('clicked').plural(counter) ``` ```dart plural('amount', counter, format: NumberFormat.currency( locale: Intl.defaultLocale, symbol: "€")), ```