我认为有两种方法可以实现你想要的。
首先是创建一个函数,将您的 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]),
);
},
...
第二个是用你的 intl 字符串创建一个数组:
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],
);
},
...
}
在不使用构建函数上下文的情况下实现此目的的另一种方法是使用StatefulWidgets 上可用的didChangeDependencies 方法,如下所示:
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)是否为空,如果是,它会将值分配给它。我们在这里使用它来避免每次都重新定义sectionTitles。