Flutter Intl plugin used with dynamic Strings

Issue

I am using the Flutter Intl plugin by Localizely to localize my App.
I generated arb files for the languages I want and begin to introduces the translations.

For example:

{
  "documentsSection": "All the documents",
  "favouritesSection": "Favourites",
  "newsSection": "News",
  "settingsSection": "Settings"
}

Everytime I want to localize a text I use:

S.of(context).favouritesSection;

And it works perfectly.

However, when I have a List like this:

List<Strings> sectionTitles = ["documentsSection","favouritesSection","newsSection","settingsSection"]

And I am inside an itemBuilder loop like this one:

itemBuilder: (context, index) {
                  String sectionName = sectionTitles[index];
                  return Text(
                      S.of(context).sectionName,
                  ),
                },

Obviously this doens’t work, as “sectionName” is not a key in the arb file. But I think that the code express what I want to achieve.
May be someone can help me.
Thanks in advance.

Solution

Another way to solve this is by using the Select ICU format kind of messages.
Note, this solution may introduce some constraints, but on the other hand, it is more elegant.

String key declaration:

"sectionTitles": "{section, select, documentsSection {Documents section} favouritesSection {Favourites section} newsSection {News section} settingsSection {Settings section} other {Section}}",
"@sectionTitles": {
  "placeholders": {
    "section": {}
  }
}

String key usage:

itemBuilder: (context, index) {
                  String sectionName = sectionTitles[index];
                  return Text(
                      S.of(context).sectionTitles(sectionName),
                  ),
                },

Answered By – Zoran Luledzija

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *