Git Product home page Git Product logo

aissat / easy_localization Goto Github PK

View Code? Open in Web Editor NEW
831.0 18.0 304.0 3.24 MB

Easy and Fast internationalizing your Flutter Apps

Home Page: https://pub.dev/packages/easy_localization

License: MIT License

Kotlin 0.07% Swift 0.70% Objective-C 0.02% Dart 89.96% Ruby 2.16% HTML 0.61% CMake 3.93% C++ 2.19% C 0.37%
flutter localization globalization i18n json flutter-apps internationalization json-files i18n-alternative translation

easy_localization's Introduction

Stand With Palestine

Easy and Fast internationalization for your Flutter Apps

Pub Version likes likes likes Code Climate issues GitHub closed issues GitHub contributors GitHub repo size GitHub forks GitHub stars Coveralls github branch GitHub Workflow Status CodeFactor Grade GitHub license Sponsors PRs Welcome StandWithPalestine

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';

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()
    );
  }
}

Full example

πŸ“œ Easy localization widget properties

Properties Required Default Description
key false Widget key.
child true Place for your main page widget.
supportedLocales true List of supported locales.
path true Path to your folder with localization files.
assetLoader false RootBundleAssetLoader() Class loader for localization files. You can use custom loaders from Easy Localization Loader or create your own class.
extraAssetLoaders false null A List of asset loaders, in case of needing assets being loaded from a different module or package. (e.g. adding a package that uses [Easy Localization Loader]).
fallbackLocale false Returns the locale when the locale is not in the list supportedLocales.
startLocale false Overrides device locale.
saveLocale false true Save locale in device storage.
useFallbackTranslations false false If a localization key is not found in the locale file, try to use the fallbackLocale file.
useFallbackTranslationsForEmptyResources false false If translation is empty in the locale file, try to use the fallbackLocale file. Does not take effect if useFallbackTranslations is false.
useOnlyLangCode false false Trigger for using only language code for reading localization files.

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

Usage

πŸ”₯ Initialize library

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

void main() async{
  // ...
  // Needs to be called so that we can await for EasyLocalization.ensureInitialized();
  WidgetsFlutterBinding.ensureInitialized();

  await EasyLocalization.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 context.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(context.tr('title'))

You can also use tr() without [Context] as a static function.

This is not recommend in build methods, because the widget won't rebuild when the language changes.

Text('title').tr() //Text widget

print('title'.tr()); //String

var title = tr('title') //Static function

Arguments:

Name Type Description
args List<String> List of localized strings. Replaces {} left to right
namedArgs Map<String, String> Map of localized strings. Replaces the name keys {key_name} according to its name
gender String Gender 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 {}"
   }
}
// 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"),

πŸ”₯ 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:

Name Type Description
value num Number value for pluralization
args List<String> List of localized strings. Replaces {} left to right
namedArgs Map<String, String> Map of localized strings. Replaces the name keys {key_name} according to its name
name String Name of number value. Replaces {$name} to value
format NumberFormat Formats 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 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

πŸ”₯ 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

Arguments Short Default Description
--help -h Help info
--source-dir -S resources/langs Folder containing localization files
--source-file -s First file File to use for localization
--output-dir -O lib/generated Output folder stores for the generated file
--output-file -o codegen_loader.g.dart Output file name
--format -f json Support json or keys formats
--[no-]skip-unnecessary-keys -u false Ignores 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';
...
void main(){
  runApp(EasyLocalization(
    child: MyApp(),
    supportedLocales: [Locale('en', 'US'), Locale('ar', 'DZ')],
    path: 'resources/langs',
    assetLoader: CodegenLoader()
  ));
}
...
  1. All done!

πŸ“¦ Localization support for multi module/package project

If you want to add localization support from other modules and packages you can add them via extraAssetLoaders parameter:

  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'),
      ],
    ));
  }

πŸ”‘ 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
//or
Text(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 function
  print('$name: ${object.toString()}');
};

/// override printer to custom
EasyLocalization.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 RTL English LTR Error widget
Arabic RTL English LTR Error 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

easy_localization's People

Contributors

3ace avatar acoutts avatar aissat avatar artemsivcev avatar bricecroix avatar bw-flagship avatar dartandrik avatar dimach1977 avatar erf avatar hatem-u avatar iwansugiarto avatar javico2609 avatar joran-dob avatar kyle-seongwoo-jun avatar kyle-tbx avatar mirankm avatar moritzmorgenroth avatar overman775 avatar petrnymsa avatar rockiedo avatar romainfranceschini avatar s19514tt avatar shrdnar avatar spiritinlife avatar tahateber95 avatar tajjacob avatar taym95 avatar themeancanehdian avatar xal avatar xurei avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

easy_localization's Issues

Log warning when trying to access missing key

When accessing a missing key, currently the lib returns the key name. But it would also be nice to log a warning stating which key is missing. This is helpful when migrating huge projects with multiple locales.

react-intl has this behaviour:
[React Intl] Missing message: "home.helloWorld" for locale: "en", using default message as fallback.

Related PR: #12

Add loadPath to load translations from backend

Hey, thank you for this awesome package, It will be nice if we can load translations files from backend, the same approach but we use http.get instead of rootBundle.loadString

example:
EasylocaLizationDelegate(locale: data.locale , path: 'resources/langs', loadPath: "https://jsonplaceholder.com/resources/langs")

{loadPath/{languageCode}-{countryCode}.json}

What do you think? I can send PR to add this feature!

From AppLocalizations.of(context).tr() to widget.tr() - major regression?

Hello,
Why such refactor was done? I think it's regression, because it's not about Widget to be translated but String itself. For example:

Previous
AppLocalizations.of(context).tr("title")
Current
Text("title").tr()

Works well. However if we go to other widget, such InputDecoration which takes argument as a String but not widget - Localization will fail.

Previous
InputDecoration(labelText: AppLocalizations.of(context).tr("someText"))

Current
InputDecoration(labelText: ???)

I think decision to move to widget level rather than string itself is not correct. Because one has to make sure lowest level is triggered - in this case String. And we shouldn't manipulate any widgets for it.

Looking forward for fix. And in the meanwhile I have to use <1.4.0 version.

Remote translation file with local asset before load?

Been using your plugin for a few hours, works nicely for now. Thanks for your work! πŸ‘

Our client will be updating by herself the translation files after app publishing, but we still need the app to load without an active internet connection.

Would it be possible to have both local asset loading and then remote locale updating?

Thanks!

setState() callback argument returned a Future

Hi when I call data.changeLocale inside setState function in a Button, this exception come up:

I/flutter (26143): ══║ EXCEPTION CAUGHT BY GESTURE β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
I/flutter (26143): The following assertion was thrown while handling a gesture:
I/flutter (26143): setState() callback argument returned a Future.
I/flutter (26143): The setState() method on _BasePageState#59c46 was called with a closure or method that returned a
I/flutter (26143): Future. Maybe it is marked as "async".
I/flutter (26143): Instead of performing asynchronous work inside a call to setState(), first execute the work (without
I/flutter (26143): updating the widget state), and then synchronously update the state inside a call to setState().
I/flutter (26143):
I/flutter (26143): When the exception was thrown, this was the stack:
I/flutter (26143): #0      State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1144:9)
I/flutter (26143): #1      State.setState (package:flutter/src/widgets/framework.dart:1160:6)
I/flutter (26143): #2      _BasePageState._showLanguagesDialog.<anonymous closure>.<anonymous closure> (package:ciloapp/pages/base/base.dart:101:28)
I/flutter (26143): #3      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:654:14)
I/flutter (26143): #4      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:729:32)
I/flutter (26143): #5      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
I/flutter (26143): #6      TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:365:11)
I/flutter (26143): #7      TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:275:7)
I/flutter (26143): #8      PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:455:9)
I/flutter (26143): #9      PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:75:13)
I/flutter (26143): #10     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:102:11)
I/flutter (26143): #11     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
I/flutter (26143): #12     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
I/flutter (26143): #13     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
I/flutter (26143): #14     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
I/flutter (26143): #15     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
I/flutter (26143): #19     _invoke1 (dart:ui/hooks.dart:263:10)
I/flutter (26143): #20     _dispatchPointerDataPacket (dart:ui/hooks.dart:172:5)
I/flutter (26143): (elided 3 frames from package dart:async)
I/flutter (26143):
I/flutter (26143): Handler: "onTap"
I/flutter (26143): Recognizer:
I/flutter (26143):   TapGestureRecognizer#3af55
I/flutter (26143): ═══════════════════════════════════════════════════════════════════

Error after hot reload

I am getting the error below when I use the hot reload. It does not occur when I compile the app from the beggining at the first time.

E/flutter (23176): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
E/flutter (23176): #0 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:314:7)
E/flutter (23176):
E/flutter (23176): #1 MethodChannel.invokeMapMethod (package:flutter/src/services/platform_channel.dart:344:48)
E/flutter (23176):
E/flutter (23176): #2 SharedPreferences._getSharedPreferencesMap (package:shared_preferences/shared_preferences.dart:158:25)
E/flutter (23176):
E/flutter (23176): #3 SharedPreferences.getInstance (package:shared_preferences/shared_preferences.dart:25:17)
E/flutter (23176):
E/flutter (23176): #4 _EasyLocalizationState.saveLocale (package:easy_localization/easy_localization_provider.dart:53:33)
E/flutter (23176):
E/flutter (23176): #5 _EasyLocalizationState.initState (package:easy_localization/easy_localization_provider.dart:36:5)
E/flutter (23176): #6 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4068:58)
E/flutter (23176): #7 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3919:5)
E/flutter (23176): #8 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3101:14)
E/flutter (23176): #9 Element.updateChild (package:flutter/src/widgets/framework.dart:2904:12)
E/flutter (23176): #10 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:998:16)
E/flutter (23176): #11 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:969:5)
E/flutter (23176): #12 RenderObjectToWidgetAdapter.attachToRenderTree. (package:flutter/src/widgets/binding.dart:915:17)
E/flutter (23176): #13 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2328:19)
E/flutter (23176): #14 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:914:13)
E/flutter (23176): #15 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:795:7)
E/flutter (23176): #16 runApp (package:flutter/src/widgets/binding.dart:845:7)
E/flutter (23176): #17 main (package:bargainer_pro/main.dart:24:3)
E/flutter (23176): #18 _runMainZoned.. (dart:ui/hooks.dart:229:25)
E/flutter (23176): #19 _rootRun (dart:async/zone.dart:1124:13)
E/flutter (23176): #20 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter (23176): #21 _runZoned (dart:async/zone.dart:1516:10)
E/flutter (23176): #22 runZoned (dart:async/zone.dart:1500:12)
E/flutter (23176): #23 _runMainZoned. (dart:ui/hooks.dart:221:5)
E/flutter (23176): #24 _startIsolate. (dart:isolate-patch/isolate_patch.dart:305:19)
E/flutter (23176): #25 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)

Locale is not changed immediately

When I run this code on my changeLocale method:

  EasyLocalizationProvider.of(context).data.changeLocale(locale);
  print("Language was changed to: " + locale.toString() +" reality:"+ EasyLocalizationProvider.of(context).data.locale.toString());

It will output:

Language was changed to: et_EE reality:en_US

Also after calling tr(key) on next build cycle it will still return translation to old language

Version: 1.4.0+2

Error importing package flutter_localizations.

I've been stuck on this issue for several days now after running flutter upgrade I get an error when importing the package flutter_localizations.

Steps to reproduce.

  • Create a new flutter project
  • Add easy_localizations to pubspec dependencies.
  • Try to import flutter_locaizations.

I've tried to run flutter upgrade, flutter packages get, flutter packages pub cache repair and restarting vs code but it did not solve the problem.

flutter doctor -v output

[βœ“] Flutter (Channel stable, v1.12.13+hotfix.8, on Linux, locale en_US.UTF-8)
 
[βœ“] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[βœ“] Android Studio (version 3.6)
[βœ“] Android Studio (version 3.5)
[!] IntelliJ IDEA Community Edition (version 2019.3)
    βœ— Flutter plugin not installed; this adds Flutter specific functionality.
    βœ— Dart plugin not installed; this adds Dart specific functionality.
[βœ“] VS Code (version 1.42.1)
[!] Connected device
    ! No devices available

! Doctor found issues in 2 categories.

Thanks in advance.

Flat json data in initial load, decreasing CPU footprint

In the current implementation, every time the user calls the tr() method, the library recursively searches through the localization tree until it finds a valid string.

We could use flat to flatten the localization map into a dot-separated map.

Example:

flatten({
  'key1': {'keyA': 'valueI'},
  'key2': {'keyB': 'valueII'},
  'key3': {
    'a': {
      'b': {'c': 2}
    }
  }
});

// {
//   'key1.keyA': 'valueI',
//   'key2.keyB': 'valueII',
//   'key3.a.b.c': 2
// };

This flat map should be saved and used across the library.

Then, accessing the array is really simple and performatic:

final key =  "my.translation.key";
final message = messages[key] ?? key; // "My awesome translated text" ?? "my.translation.key"

Save selected localization

If user have the ability to save his localization on a shared preference how to load it on application strart up?

As it always goes back to the default app unless it is overridden again on app

I can't add easy_localization package

When add "easy_localization: ^1.0.3" or "easy_localization: "1.0.3"" to pubspec.yaml file this is the error I get:

[app] flutter packages get
Running "flutter packages get" in logiztik...                   
The current Dart SDK version is 2.1.0-dev.9.4.flutter-f9ebf21297.

Because logiztik depends on easy_localization >=1.0.2+4 which requires SDK version >=2.1.0 <3.0.0, version solving failed.

pub get failed (1)
exit code 1

Fast switching languages throws an error

When I call changeLocale() in fast sequence from my application UI, it throws the error below. The file "es-US.json" does not exists, because the language code and the country code doesn't match. I did check what I am passing to changeLocale() and it is correct. No idea what is causing this error.

E/flutter (17002): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Unable to load asset: assets/langs/es-US.json
E/flutter (17002): #0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
E/flutter (17002):
E/flutter (17002): #1 AssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:67:33)
E/flutter (17002):
E/flutter (17002): #2 CachingAssetBundle.loadString. (package:flutter/src/services/asset_bundle.dart:162:56)
E/flutter (17002): #3 _LinkedHashMapMixin.putIfAbsent (dart:collection-patch/compact_hash.dart:291:23)
E/flutter (17002): #4 CachingAssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:162:27)
E/flutter (17002): #5 AppLocalizations.load (package:easy_localization/easy_localization_delegate.dart:44:31)
E/flutter (17002):
E/flutter (17002): #6 EasylocaLizationDelegate.load (package:easy_localization/easy_localization_delegate.dart:133:25)
E/flutter (17002):
E/flutter (17002): #7 _loadAll (package:flutter/src/widgets/localizations.dart:57:49)
E/flutter (17002): #8 _LocalizationsState.load (package:flutter/src/widgets/localizations.dart:508:62)
E/flutter (17002): #9 _LocalizationsState.didUpdateWidget (package:flutter/src/widgets/localizations.dart:497:7)
E/flutter (17002): #10 StatefulElement.update (package:flutter/src/widgets/framework.dart:4103:58)
E/flutter (17002): #11 Element.updateChild (package:flutter/src/widgets/framework.dart:2893:15)
E/flutter (17002): #12 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3961:16)
E/flutter (17002): #13 Element.rebuild (package:flutter/src/widgets/framework.dart:3738:5)
E/flutter (17002): #14 ProxyElement.update (package:flutter/src/widgets/framework.dart:4254:5)
E/flutter (17002): #15 Element.updateChild (package:flutter/src/widgets/framework.dart:2893:15)
E/flutter (17002): #16 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3961:16)
E/flutter (17002): #17 Element.rebuild (package:flutter/src/widgets/framework.dart:3738:5)
E/flutter (17002): #18 ProxyElement.update (package:flutter/src/widgets/framework.dart:4254:5)
E/flutter (17002): #19 Element.updateChild (package:flutter/src/widgets/framework.dart:2893:15)
E/flutter (17002): #20 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3961:16)
E/flutter (17002): #21 Element.rebuild (package:flutter/src/widgets/framework.dart:3738:5)
E/flutter (17002): #22 StatefulElement.update (package:flutter/src/widgets/framework.dart:4120:5)
E/flutter (17002): #23 Element.updateChild (package:flutter/src/widgets/framework.dart:2893:15)
E/flutter (17002): #24 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3961:16)
E/flutter (17002): #25 Element.rebuild (package:flutter/src/widgets/framework.dart:3738:5)
E/flutter (17002): #26 ProxyElement.update (package:flutter/src/widgets/framework.dart:4254:5)
E/flutter (17002): #27 Element.updateChild (package:flutter/src/widgets/framework.dart:2893:15)
E/flutter (17002): #28 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3961:16)
E/flutter (17002): #29 Element.rebuild (package:flutter/src/widgets/framework.dart:3738:5)
E/flutter (17002): #30 StatefulElement.update (package:flutter/src/widgets/framework.dart:4120:5)
E/flutter (17002): #31 Element.updateChild (package:flutter/src/widgets/framework.dart:2893:15)
E/flutter (17002): #32 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3961:16)
E/flutter (17002): #33 Element.rebuild (package:flutter/src/widgets/framework.dart:3738:5)
E/flutter (17002): #34 ProxyElement.update (package:flutter/src/widgets/framework.dart:4254:5)
E/flutter (17002): #35 Element.updateChild (package:flutter/src/widgets/framework.dart:2893:15)
E/flutter (17002): #36 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3961:16)
E/flutter (17002): #37 Element.rebuild (package:flutter/src/widgets/framework.dart:3738:5)
E/flutter (17002): #38 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2348:33)
E/flutter (17002): #39 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:760:20)
E/flutter (17002): #40 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:280:5)
E/flutter (17002): #41 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1033:15)
E/flutter (17002): #42 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:975:9)
E/flutter (17002): #43 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:891:5)
E/flutter (17002): #44 _rootRun (dart:async/zone.

How to translate String in ordinary class without return Scaffold?

I have the class for validation like here:

class Validator {

  String validateEmail(String value) {
    Pattern pattern =
        r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
    RegExp regex = new RegExp(pattern);
    if (value.length == 0 ) {
      return "Email tidak boleh kosong";
    } else if (!regex.hasMatch(value)) {
      return 'Email tidak valid';
    }
    return null;
  }

  String validatePassword(String value) {
    String pattern = r'(^[a-zA-Z0-9]*$)';
    RegExp regExp = new RegExp(pattern);
    if (value.length == 0) {
      return "Password tidak boleh kosong";
    } else if(value.length < 8){
      return "Password tidak boleh kurang dari 8";
    } else if(value.length > 15) {
      return "Password tidak boleh lebih dari 15";
    } else if (!regExp.hasMatch(value)) {
      return "Password harus menggunakan alfanumerik";
    }
    return null;
  }
}

How to translate the value of return String?

Testing with easy localization

How do we incorporate easy localization in the testing part of flutter?

It seems like EasyLocalization always needs context to make use of it, but how can we get that?

Do you have any example regarding testing?

'EasylocaLizationDelegate' typo!

Well I'm not quite sure if this can be called a 'typo',
but the capitalization (camel case) is not right.

EasylocaLizationDelegate
should be
EasyLocalizationDelegate
(the first L and second L should be switched)

I can't believe I'm the first one reporting this :)

upgrade intl package

flutter_localizations from sdk depends on intl 0.16.0, dart_json_mapper >=1.3.3 is incompatible with flutter_localizations from sdk.

Unhandled Exception: Invalid argument(s): Invalid locale 'bn_BD'

Trying to add bn_BD Bangla(Bangladesh) locale but getting a following error though I added a delegate for that locale. Please help me.

E/flutter (23735): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Invalid argument(s): Invalid locale 'bn_BD'
E/flutter (23735): #0      Intl._throwLocaleError 
package:intl/intl.dart:239
E/flutter (23735): #1      Intl.verifiedLocale 
package:intl/intl.dart:233
E/flutter (23735): #2      new DateFormat 
package:intl/…/intl/date_format.dart:246
E/flutter (23735): #3      _BnMaterialLocalizationsDelegate.load 

This is my bn locale's delegate file:

import 'dart:async';

import 'package:intl/intl.dart' as intl;
import 'package:intl/date_symbol_data_local.dart' as intl;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

class _BnMaterialLocalizationsDelegate extends LocalizationsDelegate<MaterialLocalizations> {
  const _BnMaterialLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) => locale.languageCode == 'bn' && locale.countryCode == 'BD';

  @override
  Future<MaterialLocalizations> load(Locale locale) async {
    final String localeName = intl.Intl.canonicalizedLocale(locale.toString());
    await intl.initializeDateFormatting(localeName, null);
    return SynchronousFuture<MaterialLocalizations>(
      BnMaterialLocalizations(
        localeName: localeName,
        fullYearFormat: intl.DateFormat('y', localeName),
        mediumDateFormat: intl.DateFormat('EEE, MMM d', localeName),
        longDateFormat: intl.DateFormat('EEEE, MMMM d, y', localeName),
        yearMonthFormat: intl.DateFormat('MMMM y', localeName),
        decimalFormat: intl.NumberFormat('#,##0.###', localeName),
        twoDigitZeroPaddedFormat: intl.NumberFormat('00', localeName),
      ),
    );
  }

  @override
  bool shouldReload(_BnMaterialLocalizationsDelegate old) => false;
}

class BnMaterialLocalizations extends GlobalMaterialLocalizations {
  const BnMaterialLocalizations({
    String localeName = 'bn',
    @required intl.DateFormat fullYearFormat,
    @required intl.DateFormat mediumDateFormat,
    @required intl.DateFormat longDateFormat,
    @required intl.DateFormat yearMonthFormat,
    @required intl.NumberFormat decimalFormat,
    @required intl.NumberFormat twoDigitZeroPaddedFormat,
  }) : super(
    localeName: localeName,
    fullYearFormat: fullYearFormat,
    mediumDateFormat: mediumDateFormat,
    longDateFormat: longDateFormat,
    yearMonthFormat: yearMonthFormat,
    decimalFormat: decimalFormat,
    twoDigitZeroPaddedFormat: twoDigitZeroPaddedFormat,
  );
  //added all 70 attributes
  static const LocalizationsDelegate<MaterialLocalizations> delegate = _BnMaterialLocalizationsDelegate();
}

Error on Streambuilder

when I import ease_localization on my project, all StreamBuilders don't work, worst problem is that snapshot.hasData always returns false.

I try removing easy_localization from my project and all works fine.

Return key from tr method when translation is missing

Currently AppLocalizations.of(context).tr('nonExistingKey') returns a 'null' string.
It would be nicer if it returned the missing key string (here 'nonExistingKey'), so one can recognize much easier from UI which key is missing translation. Seeing null makes it harder to detect it.

Catched bugs updating package from 1.3.1 to 1.3.3 or later versions

I use EasyLocalizationProvider.of(context).data.changeLocale() to change locale of my app and on 1.3.1 everything worked well, but as soon as I updated my package, I can't change my locale anymory. changeLocale() doesn't affect anything.

 Flutter (Channel stable, v1.12.13+hotfix.8, on Mac OS X 10.14.6 18G103, locale en-RU)
    β€’ Flutter version 1.12.13+hotfix.8 at /Users/alectogeek/Documents/Programs/flutter
    β€’ Framework revision 0b8abb4724 (8 days ago), 2020-02-11 11:44:36 -0800
    β€’ Engine revision e1e6ced81d
    β€’ Dart version 2.7.0

Android X required

Hi @aissat . It seems this library depends on version ^0.5.3+4 of the shared_preferences package. That plugin since version 0.5.0 depends on Android X. This means that any flutter apps using this plugin must also support Android X.

This isn't really a bug per say. I think it would be helpful to add this requirement to your README or remove the dependency on the shared preferences lib and perhaps use an alternative that does not require a particular version of the Android support library/Android X.

Issue with rootBundle.loadString

This is not an issue of easy_localization but of flutter framework.
Related issue here flutter/flutter#44182.

In order to allow developers to use easy_localization and also be able to test their apps maybe we should implement the proposed solution.

final ByteData byteData = await rootBundle.load(localePath);
data = utf8.decode(byteData.buffer.asUint8List());

The getter 'data' was called on null.

I do my initial config when I try to run the app I get this problem

flutter: ══║ EXCEPTION CAUGHT BY WIDGETS LIBRARY β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β• flutter: The following NoSuchMethodError was thrown building MyApp(dirty): flutter: The getter 'data' was called on null. flutter: Receiver: null flutter: Tried calling: data

I create a langs folder in the poject root and this is my assets config

assets: - images/ - langs/es-ES.json - langs/en-US.json

Throw Exception [](<key>) for plural

Version: 1.3.1

Hi, I've tried to use AppLocalizations.of(context).plural("text.day", 2) but it fails me.
Below is the structure.

{
  "text": {
    "day": {
      "zero": "day",
      "one": "day",
      "other": "days"
    }
  }
}

It seems that plural() could parse non-nested key such as day as compared to tr() which can parse text.day

Could plural() be enhanced to parse like tr()?

Lack of automated tests?

Folks,

I was just thinking of using your lib in my little project, and out of curiosity wanted to have a look at the automated tests but I have found none.
Are the tests somewhere out there and I cannot find them or they're just... not there? If not, I do not want to discourage you, but lack of test coverage is literally a show stopper for potential clients as without tests there is no way for the users of your library to maintain any level of assurance that subsequent versions of your lib will continue to behave in a consistent, predictable way.
I would also venture an opinion that the number of issues people are reporting is directly related to the lack of automated tests in the project.

Best!

The getter 'data' was called on null.

I am trying to add localization to my already existing package, but I am stuck with this error:

flutter: The following NoSuchMethodError was thrown building MyApp(dirty):
flutter: The getter 'data' was called on null.
flutter: Receiver: null
flutter: Tried calling: data

My main looks like this:

import 'package:flutter/material.dart';
import 'package:time_sheet/services/authentication.dart';
import 'package:time_sheet/pages/root_page.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter_localizations/flutter_localizations.dart';


void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var data = EasyLocalizationProvider.of(context).data;
    return EasyLocalizationProvider(
        data: data,
        child: MaterialApp(
        title: 'Flutter login demo',
        localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          //app-specific localization
          EasylocaLizationDelegate(
              locale: data.locale ?? Locale('en', 'US'),
              path: 'resources/langs'),
        ],
        supportedLocales: [Locale('en', 'US'), Locale('fr', 'CH')],
        locale: data.locale,
        debugShowCheckedModeBanner: false,
        theme: new ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: new RootPage(auth: new Auth())));
  }
}

null is not a String error

Hi @aissat,
It looks like this function in the AppLocalizations class tries to replace a null value without checking:
String tr(String key, {List<String> args}) { String res = this._resolve(key, this._sentences); if (args != null) { args.forEach((String str) { res = res.replaceFirst(RegExp(r'{}'), str); }); } return res; }

Hope you can create a fix for this.

English and Arabic in the same page

I have some pages where I have English and Arabic in the same page. The English text would become left aligned and the exclamation mark was put at the beginning of the text.

For example, a normal sentence like Wait A Minute!! would become !!Wait A Minute with the exclamation marks put in front. Is that a bug?

Complete plurals support.

For now method AppLocalizations.plural supports only .zero .one and .other. It is good for the English language. But, for example, Russian needs support of .two .few and .many.

{
  "day": {
    "zero":"{} Π΄Π½Π΅ΠΉ",
    "one": "{} дСнь",
    "two": "{} дня",
    "few": "{} дня",
    "many": "{} Π΄Π½Π΅ΠΉ",
    "other": "{} Π΄Π½Π΅ΠΉ"
  }
}

It will be perfect to delegate plurals logic to a reliable library. I chose the Intl library and it works great for me. Intl package already included in dart so there is no need for external dependencies. I replaced plural method with the following code:

String plural(String key, dynamic value) {
   final res = Intl.pluralLogic(
     value,
     zero: this._resolve(key + '.zero', this._localizedStrings),
     one: this._resolve(key + '.one', this._localizedStrings),
     two: this._resolve(key + '.two', this._localizedStrings),
     few: this._resolve(key + '.few', this._localizedStrings),
     many: this._resolve(key + '.many', this._localizedStrings),
     other: this._resolve(key + '.other', this._localizedStrings),
     locale: localeName
   );

   return res.replaceFirst(RegExp(r'{}'), '$value');
}

Method _resolve should return null if it does not find a res by key. Be cause different languages may not use some plurals.

Shared Pref Localization on re-opening not working properly

Shared Pref Localization on re-opening not working properly
as for the transalation from the dictionary works fine on the next app launch

BUT for GlobalMaterialLocalizations.delegate GlobalWidgetsLocalizations.delegate still locked on default one not by the sharedPref

how to resolve this?

Suggestions for better package maintenence

Hello to all contributors and thank you @aissat for your work here.

Since flutter is gaining traction and this package is one of the best, most feature rich, json localisation libraries at the moment, I think we need to take a moment and organise how this library should proceed and i would like to have an open discussion about this.

My suggestions/initial thoughts are:

  • Create a dev branch where all development is done. Master branch should be the latest release.
  • Add pub.dev badge Pub Version
  • Continue work on unit testing and start widget testing
  • Add code coverage information and badges?
  • Add ci for testing before merges

how to translate app title

I want ranslate app title.

child : EasyLocalizationProvider(
          data: data,
          child: MaterialApp(
            title: AppLocalizations.of(context).tr('app_title'),

but cant. how translate app title?

Use for custom widget

I have a custom widget like MyInputTextWidget, The MyInputTextWidget contains the TextField and Text for example with variable are: input text, hint, bla bla bla

How can I use localization for each custom widget?

Thanks in advanced!

Bug changing device language and recompiling app

good evening.
When using the easy_localization library I found the following bug.
When we uninstall, change the language of the device and reinstall the app, opening it causes an error. And then if we close the app and reopen it, the error does not occur again.
Steps to reproduce the error:

  1. Close the app
  2. Remove it from the emulator / device
  3. Recompile it

Flutter Doctor:
─$ β€Ήfeature/homeTabHolder*β€Ί flutter doctor -v

[βœ“] Flutter (Channel stable, v1.9.1+hotfix.4, on Linux, locale pt_BR.UTF-8)
    β€’ Flutter version 1.9.1+hotfix.4 at /opt/flutter
    β€’ Framework revision cc949a8e8b (6 weeks ago), 2019-09-27 15:04:59 -0700
    β€’ Engine revision b863200c37
    β€’ Dart version 2.5.0

 
[βœ“] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    β€’ Android SDK at /home/ark/Android/Sdk
    β€’ Android NDK location not configured (optional; useful for native profiling support)
    β€’ Platform android-29, build-tools 29.0.2
    β€’ Java binary at: /opt/android-studio/jre/bin/java
    β€’ Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
    β€’ All Android licenses accepted.

[βœ“] Android Studio (version 3.5)
    β€’ Android Studio at /opt/android-studio
    β€’ Flutter plugin version 40.1.2
    β€’ Dart plugin version 191.8423
    β€’ Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)

[βœ“] Connected device (1 available)
    β€’ Android SDK built for x86 β€’ emulator-5554 β€’ android-x86 β€’ Android 9 (API 28) (emulator)
β€’ No issues found!

StackTrace of first run app (after changing language and uninstalling it):

E/flutter (32146): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: 'dart:ui/window.dart': Failed assertion: line 281: '<optimized out>': is not true.
E/flutter (32146): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:40:39)
E/flutter (32146): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
E/flutter (32146): #2      new Locale (dart:ui/window.dart:281:15)
E/flutter (32146): #3      _EasyLocalizationState.saveLocale.<anonymous closure> (package:easy_localization/easy_localization_provider.dart:58:24)
E/flutter (32146): #4      State.setState (package:flutter/src/widgets/framework.dart:1141:30)
E/flutter (32146): #5      _EasyLocalizationState.saveLocale (package:easy_localization/easy_localization_provider.dart:57:7)
E/flutter (32146): <asynchronous suspension>
E/flutter (32146): #6      _EasyLocalizationState.initState (package:easy_localization/easy_localization_provider.dart:36:5)
E/flutter (32146): #7      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4068:58)
E/flutter (32146): #8      ComponentElement.mount (package:flutter/src/widgets/framework.dart:3919:5)
E/flutter (32146): #9      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3101:14)
E/flutter (32146): #10     Element.updateChild (package:flutter/src/widgets/framework.dart:2904:12)
E/flutter (32146): #11     RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:998:16)
E/flutter (32146): #12     RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:969:5)
E/flutter (32146): #13     RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:915:17)
E/flutter (32146): #14     BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2328:19)
E/flutter (32146): #15     RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:914:13)
E/flutter (32146): #16     WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:795:7)
E/flutter (32146): #17     runApp (package:flutter/src/widgets/binding.dart:845:7)
E/flutter (32146): #18     main (package:project_x_mobile/main.dart:8:16)
E/flutter (32146): #19     _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:229:25)
E/flutter (32146): #20     _rootRun (dart:async/zone.dart:1124:13)
E/flutter (32146): #21     _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter (32146): #22     _runZoned (dart:async/zone.dart:1516:10)
E/flutter (32146): #23     runZoned (dart:async/zone.dart:1500:12)
E/flutter (32146): #24     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:221:5)
E/flutter (32146): #25     _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:305:19)
E/flutter (32146): #26     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)
E/flutter (32146): 

StackTrace of execution letter after closing and recompiling the application (without uninstalling):

Launching lib/main.dart on Android SDK built for x86 in debug mode...
Initializing gradle...
Resolving dependencies...
Running Gradle task 'assembleDebug'...
Built build/app/outputs/apk/debug/app-debug.apk.
I/Choreographer(32242): Skipped 52 frames!  The application may be doing too much work on its main thread.
D/EGL_emulation(32242): eglMakeCurrent: 0xed6621c0: ver 2 0 (tinfo 0xe4bdb8a0)
I/OpenGLRenderer(32242): Davey! duration=1002ms; Flags=1, IntendedVsync=94286656782800, Vsync=94287523449432, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=94287528074843, AnimationStart=94287528149093, PerformTraversalsStart=94287528174343, DrawStart=94287545997033, SyncQueued=94287552389483, SyncStart=94287555768453, IssueDrawCommandsStart=94287557358083, SwapBuffers=94287580181843, FrameCompleted=94287662444533, DequeueBufferDuration=30121000, QueueBufferDuration=2144000, 
Syncing files to device Android SDK built for x86...
D/EGL_emulation(32242): eglMakeCurrent: 0xed662760: ver 2 0 (tinfo 0xe4bdbb20)

Doesnt works with web

There is no proper error in console but removing this block runs as expected

          home: MyHomePage(title: 'Home'),
          localizationsDelegates: [
            // removing this block i can run 
            EasylocaLizationDelegate(
              locale: data.locale ?? Locale('en', 'US'),
              path: 'lang'
            ),
            // block ends
            GlobalMaterialLocalizations.delegate,
          ],

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.