方法'setLocale'未为类型"_MyAppState"定义。-扑动



我试图使用按钮更改我的应用程序语言,我已经正确设置了国际化,并且我的应用是基于系统区域设置或语言工作的,现在我希望用户通过按下按钮更改语言。

所以基本上我找到了一个解决方案,其中我需要将";MyApp";在我的main.dart文件中的小部件到有状态的小部件,然后创建一个setState方法来更新locale属性的状态,这是main.dart代码:

import 'package:athaddakapp/screens/login_screen.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
static _MyAppState? of(BuildContext context) =>
context.findAncestorStateOfType<_MyAppState>();
}
class _MyAppState extends State<MyApp> {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
Locale _locale = Locale('ar', '');
void setLocale(Locale value) {
setState(() {
_locale = value;
});
}
return MaterialApp(
title: 'Login',
theme: ThemeData(
primarySwatch: Colors.purple,
),
localizationsDelegates: [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: [
Locale('en', ''), // English, no country code
Locale('ar', ''), // Arabic, no country code
],
locale: _locale,
home: LoginScreen());
}
}

这是我想从按钮更改语言时的代码:

changeLanguage() {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Center(child: Text("choose language")),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
MaterialButton(
onPressed: () => MyApp.of(context)!.setLocale(Locale.fromSubtags(languageCode: 'en')),
color: Colors.purple,
height: 50,
minWidth: MediaQuery.of(context).size.width / 2,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"English",
style: TextStyle(color: Colors.white, fontSize: 16),
),
],
),
),
SizedBox(
height: 10,
),
MaterialButton(
onPressed: () {},
color: Colors.purple,
height: 50,
minWidth: MediaQuery.of(context).size.width / 2,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"عربي",
style: TextStyle(color: Colors.white, fontSize: 16),
),
],
),
)
],
),
);
});
}
}

错误出现在这里:onPressed: () => MyApp.of(context)!.setLocale(Locale.fromSubtags(languageCode: 'en'))

现在我不确定究竟是什么类型的";MyApp";小部件应该是以及如何更改其类型。我会感谢你的帮助。

您正在将set语言环境函数放入构建函数中。将它从构建外部移动到类外部,如下所示:

class _MyAppState extends State<MyApp> {
Locale _locale = Locale('ar', '');
void setLocale(Locale value) {
setState(() {
_locale = value;
});
}
@override
Widget build(BuildContext context) {
....
}
}

最新更新