slang-i18n / slang

Type-safe i18n for Dart and Flutter
https://pub.dev/packages/slang
MIT License
459 stars 39 forks source link

How to use dynamic strings #197

Closed mariusSincovici closed 6 months ago

mariusSincovici commented 6 months ago

Hi,

I would need some help with dynamic strings. For example a service responses are only in English, how can I display that into the UI language which might not be English?

Thanks

Tienisto commented 6 months ago

Copied from the readme:

LocaleSettings.overrideTranslations(
  locale: AppLocale.en,
  fileType: FileType.yaml,
  content: r'''
onboarding
  title: 'Welcome {name}'
  '''
);

if you wish to change to English right after:

LocaleSettings.setLocale(AppLocale.en);
mariusSincovici commented 6 months ago

Thanks for the fast response, but I think I might not have explained correctly.

Translations from JSON files are compiled into dart code. But because each key from the JSON will be a variable name in dart, they cannot contain spaces. This is fine for static messages, but I would not be able to have a key "Some server message" because it will fail to compile.

As a workaround I'm converting the at runtime the server messages into some_server_message and then JSON has "some_server_message" : "Some server message". Is there a better way to have this?

As a comparison with apple they don't convert the files to code and then anything can be put as key. e.g.: English "Make Rich Text" = "Make Rich Text" German "Make Rich Text" = "In formatierten Text umwandeln";

Thanks

Tienisto commented 6 months ago

Thanks. Now I think I understood your problem.

You can mark a section of the JSON file as dynamic by adding the (map) modifier (see readme)

Example:

{
  "my_dynamic_strings(map)": {
    "some server message with spaces": "Hello",
    "another server message": "Hi"
  }
}
mariusSincovici commented 6 months ago

Thanks, I will try like this.