Update Jun 22nd:
For the generation from the arb file to class, you are looking for this package flutter_localizations
. The config is straightforward and guided in the official documentation on i18n.
If you are using Android Studio/ IntelliJ IDEA like me, there's a package called flutter_intl (Check here if you use VS Code) that allows you to generate the class in a few clicks.
For i18n integration with GetX
, simply copy the content of the arb
files to a Map
, then config it as below:
For example, here's an arb
file containing the keys:
{
"msg1": "message",
"msg2": "message",
"msg3": "message"
}
Declare variables representing your desired locales:
const Map<String, String> en = {
"msg1": "message",
"msg2": "message",
"msg3": "message"
};
const Map<String, String> fr = {
"msg1": "message_other",
"msg2": "message_other",
"msg3": "message_other"
};
Then, create a class extending Translations
from GetX
class LocalizationService extends Translations {
// Default locale
static final locale = Locale('en', 'US');
// fallback locale saves the day when the locale gets in trouble
static final fallbackLocale = Locale('fr', 'FR');
// Your supported language here
static final langs = [
'English',
'France',
];
// Supported locales (same order as above)
static final locales = [
Locale('en', 'US'),
Locale('fr', 'FR'),
];
// Keys and their translations
// Translations are defined with `en` and `fr` variable above
@override
Map<String, Map<String, String>> get keys => {
'en_US': en,
'tr_TR': fr,
};
// Use the following method to update your locale
// Gets locale from language and updates the locale
void changeLocale(String lang) {
final locale = _getLocaleFromLanguage(lang);
Get.updateLocale(locale);
}
// Finds language in `langs` list and returns it as Locale
Locale _getLocaleFromLanguage(String lang) {
for (int i = 0; i < langs.length; i++) {
if (lang == langs[i]) return locales[i];
}
return Get.locale;
}
}
Finally, define the locale in your GetMaterialApp
:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
home: HomePage(),
locale: LocalizationService.locale,
fallbackLocale: LocalizationService.fallbackLocale,
translations: LocalizationService(),
);
}
}
Use the locale as below:
Text('msg1'.tr) // The `tr` extension is from `GetX` as well