我已经尝试过answer和this one too。
在尝试翻译之前,这是下面的应用状态
我立即尝试翻译,我在屏幕上看到此错误,并且应用程序栏完全消失。
这是我的翻译功能
void _changeLanguage(AppLocalModel languageCode, BuildContext context) async {
Locale _temp;
switch (languageCode.languageCode) {
case ENGLISH:
_temp = Locale(languageCode.languageCode, "US");
break;
case JUKUN:
_temp = Locale(languageCode.languageCode, "NG");
break;
case TIV:
_temp = Locale(languageCode.languageCode, "NG");
break;
case AGATU:
_temp = Locale(languageCode.languageCode, "NG");
break;
case HAUSA:
_temp = Locale(languageCode.languageCode, "NG");
break;
default:
_temp = Locale(languageCode.languageCode, "US");
}
App.setLocale(context, _temp);
setState(() {});
}
这是我的main()
需要注意的是我的主应用是有状态的小部件,因为我有一个仅在首次启动时显示的屏幕
void main() {
runApp(App());
}
class App extends StatefulWidget {
static void setLocale(BuildContext context, Locale locale) {
_App _app = context.findAncestorStateOfType<_App>();
_app.setLocale(locale);
}
_App createState() => _App();
}
class _App extends State<App> {
Locale _locale;
void setLocale(Locale locale) {
setState(() {
_locale = locale;
});
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
getLocale().then((locale) {
this._locale = locale;
});
}
@override
void initState() {
super.initState();
getLocale().then((locale) {
this._locale = locale;
});
}
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My app',
locale: _locale,
// actions: ActionsWidget,
localizationsDelegates: [
// ... app-specific localization delegate[s] here
AppLocalization.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
localeResolutionCallback: (deviceLocale, supportedLocale) {
for (var locale in supportedLocale) {
if (locale.languageCode == deviceLocale.languageCode &&
locale.countryCode == deviceLocale.countryCode) {
return deviceLocale;
}
}
return supportedLocale.first;
},
supportedLocales: [
const Locale(ENGLISH, "US"), // English
const Locale(HAUSA, "NG"), // Housa
const Locale(AGATU, "NG"), // Hebrew
const Locale(JUKUN, "NG"), // Jukun
const Locale(TIV, "NG"), // Tiv
// ... other locales the app supports
],
home: Welcome(),
);
}
}