Flutter : The getter 'languageCode' was called on null
Asked Answered
H

2

12

I'm trying to implement localization in my app.
My app supports only two languages English and Hindi. But user can have the option to select any language from device settings other than English or Hindi. In case the user had selected any other language, I want to set the app locale to Hindi. For that, I'm using localeResolutionCallback as shown in the below code. But I'm getting the below-mentioned error message.

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)

After debugging I found that localeResolutionCallback is called twice, the 1st time the value of the locale is null and 2nd time it is giving some value.

flutter: locale---->null .

flutter: locale---->en_US .

  1. Why the localeResolutionCallback is getting called twice with a null value
  2. Is this the correct way to override the device's default locale to an app-specific locale
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(),
    );
  }
}
Hasty answered 5/9, 2019 at 13:44 Comment(4)
Did you find any solution??Subhuman
have you found a better solution, I'm having the same problemLeveloff
if you are confident enough that your code is perfect with no mistakes, then just uninstall app, flutter clean and pub get, invalidate cache and restart android studio. after that run your app, it shoud not show this error.Ulla
include the value of supportedLocales variable in your questionInsured
V
1

I have a working code of multi-language support. Please compare your code with this code. Still, if you can't figure it out, contact me for the complete source code. I have a little demo project for this thing.

class MyApp extends StatefulWidget {

  static void setLocale(BuildContext context, Locale newLocale) {
    var state = context.findAncestorStateOfType<_MyAppState>();
    state.setLocale(newLocale);
  }

  @override
  State<StatefulWidget> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {


  Locale _locale;

  void setLocale(Locale locale) {
    setState(() {
      _locale = locale;
    });
  }

  @override
  void didChangeDependencies() async {
    getLocale().then((locale) {
      setState(() {
        _locale = locale;
      });
    });
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      builder: (context, child) {
        return MediaQuery(
          child: child,
          data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
        );
      },
      title: 'Multi Language',
      debugShowCheckedModeBanner: false,
      locale: _locale,
      home: Home(),
      supportedLocales: [
        Locale('en', ''),
        Locale('ar', ''),
        Locale('hi', '')
      ],
      localizationsDelegates: [
        AppLocalizationsDelegate(),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      localeResolutionCallback: (locale, supportedLocales) {
        for (var supportedLocale in supportedLocales) {
          if (supportedLocale?.languageCode == locale?.languageCode &&
              supportedLocale?.countryCode == locale?.countryCode) {
            return supportedLocale;
          }
        }
        return supportedLocales?.first;
      },
    );
  }
}
Vermiform answered 3/10, 2022 at 5:2 Comment(0)
D
0

I found a solution but this will only force your app to the default language

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;

I will try to find a better solution soon I will let you know. With android devices locale returns the default phone language but in iOs is where this error comes up.

Deen answered 20/11, 2019 at 15:42 Comment(1)
have you found a better solution, I'm having the same problem?Leveloff

© 2022 - 2024 — McMap. All rights reserved.