I think there are two ways to achieve what you want.
The first is creating a function that maps your sectionTitles
to your intl strings, something like this:
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;
}
}
And using like this:
...
itemBuilder: (context, index) {
return Text(
getSectionTitle(context, sectionTitles[index]),
);
},
...
The second is making an array with your intl strings:
List<String> sectionTitles = [
S.of(context).documentsSection,
S.of(context).favouritesSection,
S.of(context).newsSection,
S.of(context).settingsSection,
];
But you would need to create this inside your build function because you need a context:
@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],
);
},
...
}
Another way of achieving this without using the context from your build function is by using the didChangeDependencies
method available on StatefulWidgets
, like this:
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],
);
},
...
}
Note that in this case, you cannot use initState
because it wouldn't provide a context with the intl strings already available, thus we use didChangeDependencies
.
If you are wondering what does the ??=
does, it simply checks if a variable (in this case sectionTitles
) is null, and if it is, it will assign the values to it. We use it here to avoid redefining the sectionTitles
every time.