Flutter-在null上调用了方法'changeLanguage'

时间:2020-03-23 04:23:07

标签: flutter localization

我是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”)); 行上引发了错误。我不确定为什么它为空。我希望有人可以帮助我:(

0 个答案:

没有答案