我是新手,正在尝试对我的应用实施本地化。 我的应用程序仅支持英语和北印度语两种语言。但是用户可以选择从设备设置中选择除英语或印地语以外的任何语言。如果用户选择了任何其他语言,我想将应用程序的语言环境设置为印地语。为此,我使用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)
调试之后,我发现localeResolutionCallback被调用了两次,第一次是locale的值为null,第二次是给定值。
flutter:语言环境----> null。
flutter:语言环境----> en_US。
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;
}
}
// If the locale of the device is not supported, use the first one
// from the list (English, in this case).
return supportedLocales.last;
},
home: DemoApp(),
);
}
}
答案 0 :(得分: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;
我会尽快找到更好的解决方案,让您知道。使用android设备时,语言环境会返回默认电话语言,但在iOs中会出现此错误。
答案 1 :(得分:0)
如果未检测到语言环境则发送null很好,但是不好则接收第一个null,并在毫秒后接收正确的语言。我认为检测中有问题,它会尝试在应用初始化之前检测语言环境?
所以这段代码可以正常工作,除了它首先以默认lang开始,然后以正确的语言环境开始。
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;
}
此答案来自gimox