我正在使用Localizely的Flutter Intl插件来本地化我的应用程序。我为所需的语言生成了arb文件,并开始介绍翻译。
例如:
{
"documentsSection": "All the documents",
"favouritesSection": "Favourites",
"newsSection": "News",
"settingsSection": "Settings"
}
每次我想本地化我使用的文本:
S.of(context).favouritesSection;
而且效果很好。
但是,当我有这样的列表时:
List<Strings> sectionTitles = ["documentsSection","favouritesSection","newsSection","settingsSection"]
而且我在这样的itemBuilder循环中:
itemBuilder: (context, index) {
String sectionName = sectionTitles[index];
return Text(
S.of(context).sectionName,
),
},
显然,这不起作用,因为“ sectionName”不是arb文件中的键。但是我认为代码表达了我想要实现的目标。可能有人可以帮助我。预先感谢。
您是否尝试过使用S.of(context)[sectionName]
?
我认为有两种方法可以实现您想要的。
首先是创建一个将sectionTitles
映射到intl字符串的函数,如下所示:
String getSectionTitle(BuildContext context, String title) {
if (title == "documentsSection") {
return S.of(context).documentsSection;
} else if (title == "favouritesSection") {
return S.of(context).favouritesSection;
} else if (title == "newsSection") {
return S.of(context).newsSection;
} else if (title == "settingsSection") {
return S.of(context).settingsSection;
}
}
并且像这样使用:
...
itemBuilder: (context, index) {
return Text(
getSectionTitle(context, sectionTitles[index]),
);
},
...
第二个是使用您的国际字符串创建数组:
List<String> sectionTitles = [
S.of(context).documentsSection,
S.of(context).favouritesSection,
S.of(context).newsSection,
S.of(context).settingsSection,
];
但是您需要在构建函数中创建此文件,因为您需要上下文:
@override
Widget build(BuildContext context) {
List<String> sectionTitles = [
S.of(context).documentsSection,
S.of(context).favouritesSection,
S.of(context).newsSection,
S.of(context).settingsSection,
];
return ...
itemBuilder: (context, index) {
return Text(
sectionTitles[index],
);
},
...
}
不使用构建函数的上下文即可实现的另一种方法是使用didChangeDependencies
上可用的StatefulWidgets
方法,如下所示:
List<String> sectionTitles;
@override
void didChangeDependencies() {
super.didChangeDependencies();
sectionTitles ??= [
S.of(context).documentsSection,
S.of(context).favouritesSection,
S.of(context).newsSection,
S.of(context).settingsSection,
];
}
@override
Widget build(BuildContext context) {
return ...
itemBuilder: (context, index) {
return Text(
sectionTitles[index],
);
},
...
}
请注意,在这种情况下,您不能使用initState
,因为它不会提供具有可用的intl字符串的上下文,因此我们使用didChangeDependencies
。
[如果您想知道??=
的作用,它只是检查变量(在这种情况下为sectionTitles
)是否为null,如果为null,它将为其分配值。我们在这里使用它来避免每次都重新定义sectionTitles
。