aissat / easy_localization

Easy and Fast internationalizing your Flutter Apps
https://pub.dev/packages/easy_localization
MIT License
923 stars 332 forks source link

Translate String into specific language #531

Open LuNiPriSe opened 2 years ago

LuNiPriSe commented 2 years ago

Hi,

I translated my APP successfully with easy_localization.

My problem is that I want to save single notifications in the language of the notification-receiver not the sender.

So I would need something like .tr("de") or so to send it correctly.

Somehow it doesn't work to do: setlocale(receiver_lang) send notification setlocale(sender_lang)

The notification is always send in the sender_lang.

I tried to await and to (combine) .then(...). With one I get the receiver_lang, but the change back is ignored. If I chain the .then I get an error of "Looking up a deactivated widget's ancestor is unsafe...) Maybe it is an issue, because I try inside an onTap?

How would I translate single Strings into a specific language different of the locale?

AekaderFELLAGUE commented 2 years ago

I'm running into the same problem, any solutions?

felix0324324 commented 1 year ago

same problem

majlindavdylaj commented 1 year ago

I found a solution its not the best but works

class AppLocale {

  static const String path = 'assets/translations';

  static Future<String> translate(BuildContext context, {locale, key}) async {
    String lang = context.supportedLocales.contains(locale!)
        ? locale.languageCode : context.fallbackLocale!.languageCode;
    final String response = await rootBundle.loadString('$path/$lang.json');
    final Map<String, dynamic> data = await json.decode(response);
    return (data[key] ?? 'Not found').toString();
  }

}

Now you can translate String msg = await AppLocale.translate(context, locale: Locale('en'), key: 'message');

devnneth commented 2 months ago

Thank you @majlindavdylaj.

I made a small modification to your code for dot access.

class AppLocale {
  static dynamic nestedAccess(Map data, String key) {
    return key.split('.').fold(data, (dynamic acc, String part) => acc[part]);
  }

  static Future<String> translate(context, lang, key) async {
    final String response =
        await rootBundle.loadString('assets/translations/$lang.json');
    final Map<String, dynamic> data = await json.decode(response);
    return (nestedAccess(data, key) ?? 'Not found').toString();
  }
}

String msg = await AppLocale.translate(context, "ko", 'settings.lang_changed');
print(msg);