class ChangeLanguage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Change Language'),
),
body: Center(
child: RaisedButton(
child: Text('Change'),
onPressed: () {
navigator.pop(context);
},
),
),
);
}
答案 0 :(得分:0)
如果您想在不重新启动应用程序且没有任何插件的情况下更改应用程序语言,则可以按照以下步骤操作:
在应用程序的主文件中,例如在StatefullWedget
中创建MyHomePage
方法static
,如下所示
setLocal
其中class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
static void setLocale(BuildContext context, Locale newLocale) async {
_MyHomePageState state =
context.findAncestorStateOfType<_MyHomePageState>();());
state.changeLanguage(newLocale);
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
是您的_MyHomePageState
小部件的state
在您的MyHomePage
中创建一个state
方法static
:
changeLanguage
现在,您可以在应用程序页面中通过调用 class _MyHomePageState extends State<MyHomePage> {
Locale _locale;
changeLanguage(Locale locale) {
setState(() {
_locale = locale;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Afghanistan',
theme: ThemeData(primaryColor: Colors.blue[800]),
supportedLocales: [
Locale('fa', 'IR'),
Locale('en', 'US'),
Locale('ps', 'AFG'),
],
locale: _locale,
localizationsDelegates: [
AppLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate
],
localeResolutionCallback: (locale, supportedLocales) {
for (var supportedLocale in supportedLocales) {
if (supportedLocale.languageCode == locale.languageCode &&
supportedLocale.countryCode == locale.countryCode) {
return supportedLocale;
}
}
return supportedLocales.first;
},
initialRoute: splashRoute,
onGenerateRoute: Router.generatedRoute,
);
}
}
方法来更改语言,并按如下所示传递新的setLocal
:
Locale
请记住,您需要创建一个Locale newLocale = Locale('ps', 'AFG');
MyHomePage.setLocale(context, newLocale);
,
Here是演示应用程序的链接