我正在使用flutter构建一个基于阿拉伯语的应用程序(RTL语言(,我想有一种方法比在像Directionality(textDirection: TextDirection.rtl, child: FacultyPage())
这样的每个页面中使用Directionality
更好,因为我觉得这不是一种干净的方法,有时我忘了将Directionality
作为父窗口小部件来实现,尤其是在有很多页面/屏幕的大型应用程序中。
因此,默认布局变为RTL,无需通过Directionality
对每个屏幕/页面进行重做。
为整个应用程序设置RTL
配置的最简单方法是:
void main() {
runApp(
MaterialApp(
home: Directionality( // use this
textDirection: TextDirection.rtl, // set it to rtl
child: HomePage(),
),
),
);
}
在不定义Directionality
小部件的情况下,在应用程序中设置方向性最干净的方法是使用本地化委托。
请参阅下面的示例。
my_localization_delegate.dart
class MyLocalizationDelegate
extends LocalizationsDelegate<WidgetsLocalizations> {
final MyLocalization mylocalization;
MyLocalizationDelegate(this.myLocalization);
@override
bool isSupported(Locale locale) => true;
@override
Future<WidgetsLocalizations> load(Locale locale) async => mylocalization
@override
bool shouldReload(MyLocalizationDelegate old) => false;
}
my_localization.dart
class MyLocalization implements WidgetsLocalizations {
@override
TextDirection get textDirection {
// logic to return the correct directionality
}
}
your_app.dart
final MyLocalization _myLocalization = Mylocalization();
final MyLocalizationDelegate _myLocalizationDelegate = MyLocalizationDelegate(_myLocalization);
...
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: [_myLocalizationDelegate],
...
使用本地化和国际化
当您在Main MyApp state MaterialApp中指定阿拉伯语语言环境时,它将更改应用程序子树中每个小部件的方向性。
Flutter文档链接中解释得很好
在本地化和Intl依赖项之后,您可以在myApp状态MaterialApp中定义和设置阿拉伯语的Locale。
我已经在Parent MyApp中使用findAncestorStateOfType在Child 中设置Locale
这是代码
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
static void setLocale(BuildContext context, Locale locale) {
_MyAppState? state = context.findAncestorStateOfType<_MyAppState>();
state!.setLocale(locale);
}
@override
_MyAppState createState() => _MyAppState();
}
// ignore: use_key_in_widget_constructors
class _MyAppState extends State<MyApp> {
// const MyApp({Key? key}) : super(key: key)
late Locale _locale;
void setLocale(Locale value) {
setState(() {
_locale = value;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: const [
AppLocalizations.delegate, // Add this line
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [
Locale('en', ''), // English, no country code
Locale('ar', ''), // Spanish, no country code
],
locale: _locale,
themeMode: ThemeMode.light,
// themeMode: ThemeMode.dark,
// themeMode: ThemeMode.system,
theme: MyTheme.lightTheme(context),
darkTheme: MyTheme.darkTheme(context),
debugShowCheckedModeBanner: false,
initialRoute: "/",
routes: {
"/": (context) => LoginScreen1(), //LoginPage(),
MyRoutes.loginRoute: (context) => LoginScreen1(), //LoginPage(),
MyRoutes.signupRoute: (context) => const SignUpScreen1(),
MyRoutes.homeRoute: (context) => HomePage(),