I have lots of getters for localizations (they are coming from the json file for example) such as:
String get start {
return localizedValues[locale.languageCode]!['start']!;
}
String get hours {
return localizedValues[locale.languageCode]!['hours']!;
}
String get minutes {
return localizedValues[locale.languageCode]!['minutes']!;
}
String get seconds {
return localizedValues[locale.languageCode]!['seconds']!;
}
So I want to compound them since they use some common codes (I tried to create final someWord = commonCode; but It did not work, so I wanted to ask)
Now, If I want to reach them, I use myClass.of(context).start for example. So, in the end, I will reach using the same way but in the class which is above, I will not do any duplication If you help me. So, I need your help to avoid duplication.
CodePudding user response:
You can use this method, and shorten the code:
String getTime(String languageCode, String time) {
return localizedValues[languageCode]![time]!;
}
getTime("1529", "seconds");
getTime("859", "mitutes");
getTime("9632", "hours");
CodePudding user response:
I would recommend using a data class to hold localisation data instead of just a Map, or using a package such as i10n to do the translations for you.
There are a couple of ways you can shorten this code. For starters, you can extract localizedValues[locale.languageCode]!
to its own getter, like this:
Map<String, String> get localeValues => localizedValues[locale.languageCode]!;
Then all your methods become a bit shorter:
String get seconds {
return localeValues['seconds']!;
}
Additionally, you can shorten your getters by removing the function body and using an arrow function instead, like I did above for the localeValues
:
String get seconds => localeValues['seconds']!;
Do this for all your getters, and your code is now shorter.