how to get current layout direction in Flutter?
Asked Answered
B

2

8

I'm working on an application that should also work with RTL layout direction (Arabic and Hebrew languages).

I also need to perform some changes in the layout in case the layout direction is RTL.

How can I determine what is the current layout direction of the app?

Bainmarie answered 23/1, 2020 at 21:25 Comment(1)
@xxx what is the connection to the question you posted? the question you posted talks about screen orientation (meaning portrait or landscape). My question is regarding layout direction (meaning left-to-right or right-to-left). Please validate that the question is indeed duplicate before you flag it as one!Bainmarie
S
22

You can get the current direction using Directionality.of.

final TextDirection currentDirection = Directionality.of(context);
final bool isRTL = currentDirection == TextDirection.rtl;

which determines `the direction of the selctedlanguage but if need you to set it manually, probably this can work for you.

Widget build(BuildContext context) {
  return MaterialApp(
    debugShowCheckedModeBanner: false,
    theme: ThemeData(),
    home: Directionality(
      textDirection: TextDirection.rtl,
      child: Home(),
    ),
  );
}
Shelia answered 24/1, 2020 at 22:54 Comment(0)
D
3
  1. Add this method to your class :

bool isRTL() => Directionality.of(context).toString().contains(TextDirection.RTL.value.toLowerCase());

  1. Usage in the build() method :

RichText(
   textAlign: isRTL() ? TextAlign.right : TextAlign.left,
   .....
),

Dempsey answered 20/12, 2020 at 8:53 Comment(1)
i have simplified it to bool isRtl = Directionality.of(context).index == 0;Unblushing

© 2022 - 2024 — McMap. All rights reserved.