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'),
TechHelper
  • 822
  • 10
  • 24

1 Answers1

1

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;
  }
}
dm_tr
  • 4,265
  • 1
  • 6
  • 30
  • And then to apply the translation you can write `Translator.of(context).translate("gd_morning", args: ["TechHelper"]);` – dm_tr Dec 22 '20 at 20:32
  • 1
    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? – TechHelper Dec 23 '20 at 09:04
  • 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` – dm_tr Dec 23 '20 at 10:07
  • 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. – TechHelper Dec 24 '20 at 07:04
  • Feel free. Also if it answer your question you can mark it as the correct answer to help future readers. Happy coding – dm_tr Dec 24 '20 at 10:11