Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Change default textDirection on the whole app to RTL

I'm building an Arabic based app (RTL language) using flutter and I guess there is a way better than using Directionality in each page like this Directionality(textDirection: TextDirection.rtl, child: FacultyPage()) as I don't feel it's a clean approach and sometimes I forget to implement Directionality as parent widget especially in large apps with a lot of pages/screens.

So the default layout becomes RTL no need to redoing it by Directionality each screen/page.

like image 495
hesham shawky Avatar asked Oct 20 '25 15:10

hesham shawky


2 Answers

The easiest way to set RTL configuration for the entire app is:

void main() {
  runApp(
    MaterialApp(
      home: Directionality( // use this
        textDirection: TextDirection.rtl, // set it to rtl 
        child: HomePage(),
      ),
    ),
  );
}
like image 114
CopsOnRoad Avatar answered Oct 22 '25 04:10

CopsOnRoad


The cleanest way to set directionality across the app without defining Directionality widget(s) is to use localizations delegate.

See example below.

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],

 ...
like image 23
CuriousSuperhero Avatar answered Oct 22 '25 03:10

CuriousSuperhero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!