6月22日更新:
对于从 arb 文件到类的生成,您正在寻找这个包flutter_localizations
。配置很简单,并在 i18n的官方文档中提供指导。
如果您像我一样使用 Android Studio/IntelliJ IDEA,则有一个包调用flutter_intl(如果您使用 VS Code,请在此处查看),它允许您单击几下即可生成类。
对于 i18n 与 GetX 的集成,只需将arb
文件的内容复制到 a Map
,然后进行如下配置:
例如,这是一个arb
包含密钥的文件:
{
"msg1": "message",
"msg2": "message",
"msg3": "message"
}
声明代表您想要的语言环境的变量:
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"
};
然后,创建一个Translations
从GetX
class LocalizationService extends Translations {
// Default locale
static final locale = Locale('en', 'US');
// fallbackLocale 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;
}
}
最后,在您的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(),
);
}
}
使用如下语言环境:
Text('msg1'.tr) // The `tr` extension is from `GetX` as well