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 .
- Why the
localeResolutionCallback
is getting called twice with a null value - 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(),
);
}
}
supportedLocales
variable in your question – Insured