flutterdartright-to-lefttext-renderingleft-to-right

What does TextDirection really do in Flutter


What difference does using TextDirection make. It's required all over the place in Flutter but the purpose isn't clear.

For example, given the following code:

const text = 'Hello';
final textSpan = const TextSpan(
  text: text,
  style: TextStyle(fontSize: 50, color: Colors.black),
);

final TextPainter textPainter = TextPainter()
  ..textDirection = TextDirection.ltr
  ..text = textSpan
  ..layout();
textPainter.paint(canvas, Offset(0, 0));

The text direction is set to TextDirection.ltr. This prints Hello.

However, setting the text direction to TextDirection.rtl doesn't give olleH. It's still Hello. So what is the purpose of TextDirection?


Solution

  • TextDirection doesn't change the order of characters within left-to-right (LTR) text like English or Russian. Neither does it change the order of characters within right-to-left (RTL) text like Arabic or Hebrew.

    What TextDirection does is changes the order blocks of LTR and RTL text when they occur in the same string, that is, as bidirectional text.

    You can see this in the following example:

    const text = 'Hello שלום';
    

    That string contains both LTR text (Hello) and also RTL text (שלום). The LTR text comes at the beginning of the string. So when you are in an LTR environment Hello should be painted on the left (first) and שלום on the right (last).

    Indeed, you can observe this to be true:

    const text = 'Hello שלום';
    final textSpan = const TextSpan(
      text: text,
      style: TextStyle(fontSize: 30, color: Colors.black),
    );
    final TextPainter textPainter = TextPainter()
      ..textDirection = TextDirection.ltr  //       <-- LTR
      ..text = textSpan
      ..layout();
    textPainter.paint(canvas, Offset(0, 0));
    

    This results in:

    enter image description here

    But change the direction to TextDirection.rtl and you'll get the following result:

    enter image description here

    The Hello is still first but since the environment is RTL now, this means first is on the right. The שלום is still last but now last is on the left. Interestingly, the space is maintained between them.