Flutter Intl 插件与动态字符串一起使用

jRu*_*MoL 3 flutter flutter-intl

我正在使用 Localizely 的 Flutter Intl 插件来本地化我的应用程序。我为我想要的语言生成了 arb 文件并开始介绍翻译。

例如:

{
  "documentsSection": "All the documents",
  "favouritesSection": "Favourites",
  "newsSection": "News",
  "settingsSection": "Settings"
}
Run Code Online (Sandbox Code Playgroud)

每次我想本地化我使用的文本时:

S.of(context).favouritesSection;
Run Code Online (Sandbox Code Playgroud)

它完美地工作。

但是,当我有这样的列表时:

List<Strings> sectionTitles = ["documentsSection","favouritesSection","newsSection","settingsSection"]
Run Code Online (Sandbox Code Playgroud)

我在这样一个 itemBuilder 循环中:

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

显然这不起作用,因为“sectionName”不是 arb 文件中的键。但我认为代码表达了我想要实现的目标。可能有人可以帮助我。提前致谢。

小智 6

解决此问题的另一种方法是使用Select ICU 格式的消息。
请注意,此解决方案可能会引入一些约束,但另一方面,它更优雅。

字符串键声明:

"sectionTitles": "{section, select, documentsSection {Documents section} favouritesSection {Favourites section} newsSection {News section} settingsSection {Settings section} other {Section}}",
"@sectionTitles": {
  "placeholders": {
    "section": {}
  }
}
Run Code Online (Sandbox Code Playgroud)

字符串键用法:

"sectionTitles": "{section, select, documentsSection {Documents section} favouritesSection {Favourites section} newsSection {News section} settingsSection {Settings section} other {Section}}",
"@sectionTitles": {
  "placeholders": {
    "section": {}
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @Ced我知道有点晚了,但是[这里(链接)](https://lokalise.com/blog/complete-guide-to-icu-message-format/#Switch_with_select)是 **Select 的解释** 格式。基本上是这样的: `{varName, select, optionOne {第一个选项的翻译} secondaryOption {第二个选项的翻译} other {在给出此文本之前没有匹配到的内容}}` (2认同)