I'm trying to implement localisation to my app.
My app supports only two language English and Hindi. But user can have option to select any language from device settings other than English or Hindi. In case 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 , 1st time the value of locale is null and 2nd time it is giving some value.
flutter: locale---->null .
flutter: locale---->en_US .
localeResolutionCallback
is getting called twice with null valueclass 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(),
);
}
}
send null if locale is not detected is good, but is not good receive first null and after a milliseconds the correct language. I think there is something wrong in detection, it try to detect locale before app init?
So this code work good except that it start first with default lang and after with correct locale.
localeResolutionCallback (Locale locale, Iterable<Locale> supportedLocales) {
if (locale == null) {
debugPrint("*language locale is null!!!");
return supportedLocales.first;
}
for (Locale supportedLocale in supportedLocales) {
if (supportedLocale.languageCode == locale.languageCode ||
supportedLocale.countryCode == locale.countryCode) {
debugPrint("*language ok $supportedLocale");
return supportedLocale;
}
}
debugPrint("*language to fallback ${supportedLocales.first}");
return supportedLocales.first;
}
this answer adopted from : gimox
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With