Translations in Flutter Package
If you need to have translations in your Flutter package and you can't use solutions like recommended localization delegate in MaterialApp
or you can't use solutions like easy_localizations
, you can try doing your own simple translations service.
Let's define translations model. It's quite simple - we're storing language code and map of translations:
class TranslationData {
final String languageCode;
final Map<TranslationKey, String> values;
TranslationData({required this.languageCode, required this.values});
}
TranslationKey
is simple enum with all possible translation keys from your domain:
enum TranslationKey{
list,
details
}
Next, you need to create your translations service:
import 'package:translations/translation_data.dart';
import 'package:translations/translation_key.dart';
class Translations {
static final List<TranslationData> _translations = _initialise();
static String get({
required String languageCode,
required TranslationKey key,
}) {
try {
final data = _translations.firstWhere(
(element) => element.languageCode == languageCode,
orElse: () => _translations.first,
);
final value = data.values[key] ?? key.toString();
return value;
} catch (error) {
return key.toString();
}
}
static List<TranslationData> _initialise() {
final translations = <TranslationData>[];
translations.add(_getEnTranslations());
translations.add(_getPlTranslations());
return translations;
}
static TranslationData _getEnTranslations() {
return TranslationData(languageCode: "en", values: {
TranslationKey.details: "Details screen",
TranslationKey.list: "List screen"
});
}
static TranslationData _getPlTranslations() {
return TranslationData(languageCode: "pl", values: {
TranslationKey.details: "Ekran detaili",
TranslationKey.list: "Ekran listy"
});
}
}
In this service we're initialising translations for English and Polish languages. Then in get
method we're translating key
for a given languageCode
. If languageCode
can't be found, we're using first configured language which is English.
Now, we can access our translations by calling:
Translations.get("en", TranslationKey.details);
We're still missing one thing - automatic way to get language code. We can fix that, by adding extension:
extension TranslationKeyExt on TranslationKey{
String tr(){
final locale = Platform.localeName;
final languageCode = locale.split("_").first;
return Translations.get(languageCode: languageCode,key: this);
}
}
Now you can call TranslationKey.details.tr()
to get value translated.