我是Flutter的新手,我想进行应用内本地化。我尝试按照HERE的步骤进行操作,并设法根据手机的语言环境进行本地化。
但是,当我尝试进行应用内本地化时,出现了此错误:
The method 'changeLanguage' was called on null.
Receiver: null
Tried calling: changeLanguage(Instance of 'Locale')
下面是我的代码部分,我将其称为changeLanguage:
void _showLanguageBottomSheet() {
AppLanguage appLanguage = Provider.of<AppLanguage>(context);
showModalBottomSheet(
isScrollControlled: false,
backgroundColor: Colors.transparent,
context: context,
builder: (builder) {
return Container(
padding: const EdgeInsets.fromLTRB(15, 20, 15, 15),
decoration: BoxDecoration(
color: Palette.white,
borderRadius: BorderRadius.only(
topLeft: const Radius.circular(15),
topRight: const Radius.circular(15),
)),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
// Title
Text(
"${AppLocalizations.of(context).translate('change_language')}",
style: CustomTextStyle.blackLargeBoldText),
SizedBox(height: 10),
// Buttons
Row(children: <Widget>[
GestureDetector(
child: englishLabel(),
onTap: () {
englishSelected = true;
Navigator.pop(context);
appLanguage.changeLanguage(Locale("en"));
},
),
SizedBox(width: 15),
GestureDetector(
child: chineseLabel(),
onTap: () {
englishSelected = false;
Navigator.pop(context);
appLanguage.changeLanguage(Locale("zh"));
})
])
],
),
);
});
}
下面是AppLanguage类中的changeLanguage函数。我完全遵循此link中的教程:
void changeLanguage(Locale type) async {
var prefs = await SharedPreferences.getInstance();
if (_appLocale == type) {
return;
}
if (type == Locale("zh")) {
_appLocale = Locale("zh");
await prefs.setString('language_code', 'zh');
await prefs.setString('countryCode', 'Hans');
} else {
_appLocale = Locale("en");
await prefs.setString('language_code', 'en');
await prefs.setString('countryCode', 'UK');
}
notifyListeners();
}
当我尝试调试时,代码甚至没有通过changeLanguage函数。在 appLanguage.changeLanguage(Locale(“ zh”)); 或 appLanguage.changeLanguage(Locale(“ en”)); 行上引发了错误。我不确定为什么它为空。我希望有人可以帮助我:(