Flutter:在 null 上调用了 getter 'languageCode'

cha*_*dan 10 localization flutter

我正在尝试对我的应用实施本地化。
我的应用程序仅支持英语和印地语两种语言。但用户可以选择从设备设置中选择除英语或印地语以外的任何语言。如果用户选择了任何其他语言,我想将应用程序区域设置为印地语。为此,我正在使用localeResolutionCallback如下代码所示。但是我收到了下面提到的错误消息。

flutter: ??? EXCEPTION CAUGHT BY WIDGETS LIBRARY ????????????????????????????????????????????????????????????
flutter: The following NoSuchMethodError was thrown building ScrollConfiguration(behavior:
flutter: _MaterialScrollBehavior):
flutter: The getter 'languageCode' was called on null.
flutter: Receiver: null
flutter: Tried calling: languageCode
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:50:5)
flutter: #1      Demo.build.<anonymous closure> (package:simple/main.dart:49:54)
Run Code Online (Sandbox Code Playgroud)

调试后我发现它localeResolutionCallback被调用了两次,第一次 locale 的值为空,第二次它给出了一些值。

颤振:语言环境----> null 。

颤振:语言环境----> en_US 。

  1. 为什么localeResolutionCallback用空值调用两次
  2. 这是将设备默认语言环境覆盖为应用程序特定语言环境的正确方法吗
class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      onGenerateTitle: (BuildContext context) => AppLocalizations.of(context).title,
      localizationsDelegates: [
        AppLocalizationsDelegate(),
        GlobalWidgetsLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('en', ''), // English
        const Locale('hi', ''), // hindi
      ],
      localeResolutionCallback: (locale, supportedLocales) {
        for (var supportedLocale in supportedLocales) {
          if (supportedLocale.languageCode == locale.languageCode &&
              supportedLocale.countryCode == locale.countryCode) {
            return supportedLocale;
          }
        }
        return supportedLocales.last;
      },
      home: DemoApp(),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 0

我找到了一个解决方案,但这只会强制您的应用程序使用默认语言

for (var supportedLocale in supportedLocales) {
      if (locale!=null && locale.languageCode!=null && locale.countryCode!=null && supportedLocale.languageCode == locale.languageCode &&
          supportedLocale.countryCode == locale.countryCode){
        return supportedLocale;
      }
    }
    // If the locale of the device is not supported, or locale returns null
    // use the last one from the list (Hindi, in your case).
    return supportedLocales.last;
Run Code Online (Sandbox Code Playgroud)

我会尽快找到更好的解决方案,我会让您知道。对于 Android 设备,区域设置会返回默认的手机语言,但在 iO 中会出现此错误。