0

Flutter localization: Can we directly replace some regex pattern in string to get dynamic string using json language files instead of using .arb files to avoid so many overheads of using .arb? Is there any limitation in this approach of direct replace and use instead of arb & Intl library?

"gd_morning": "Good Morning {name}",

AppLocalizations.of(context)
                .get('gd_morning')
                .replaceAll('{name}', 'My Name'),

1 Answer 1

2

Yes it's possible. Have a try with this.
This assumes that your json contents something like "gd_morning": "Good Morning {0}" for instance

String translate(String key, {List<dynamic> args}) {
  if (null == _translatedStrings[key]) return "${locale.languageCode}[$key]";
  _translatedKey = _translatedStrings[key];
  if (null == args || args.isEmpty) return _translatedKey;
  else {
    for(int i = 0; i < args.length; ++i) _translatedKey = _translatedKey.replaceAll("{$i}", args[i]);
    return _translatedKey;
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

And then to apply the translation you can write Translator.of(context).translate("gd_morning", args: ["TechHelper"]);
Thanks @dm_tr.Yes, i am doing similar now. But I want to ask that if this is proper way and will work seamlessly in all the situations? Or we will need localization using .arb file & Intl library to support every case and situation?
It works in all situations even if you change the order of the values like {0} Good morning. The result will be in this case TechHelper Good morning
I am continuing using replace logic for now. Let's see how it works in every situation. If i face any problem I will update it here.
Feel free. Also if it answer your question you can mark it as the correct answer to help future readers. Happy coding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.