Open6

FlutterのTextのtextAlignとtextDirectionの違い

matsuchiyomatsuchiyo
  • 日本語と英語に対応したメモアプリを出している。
  • 今回、あるユーザーからヘブライ語のように右から左に書く言語のメモでは、メモの本文を左寄せではなく、右寄せにして欲しいと問い合わせをもらった。
  • そこでFlutterのText周りを調べていたところ、今回使いそうなものとして、textAlignとtextDirectionがあった。
  • この違いがよくわからないので、スクラップとして残す。
matsuchiyomatsuchiyo

まずtextAlignについて

  • TextのtextAlign property

    How the text should be aligned horizontally.

    • TextAlign enum
      • テキストをコンテナの先頭に揃える。先頭は、TextDirection.ltrなら左、rtlなら右になる。

        start → const TextAlign
        Align the text on the leading edge of the container.
        For left-to-right text (TextDirection.ltr), this is the left edge.
        For right-to-left text (TextDirection.rtl), this is the right edge.

matsuchiyomatsuchiyo

次にtextDirectionについて

  • textDirection property

    This decides how textAlign values like TextAlign.start and TextAlign.end are interpreted.

    This is also used to disambiguate how to render bidirectional text. For example, if the data is an English phrase followed by a Hebrew phrase, in a TextDirection.ltr context the English phrase will be on the left and the Hebrew phrase to its right, while in a TextDirection.rtl context, the English phrase will be on the right and the Hebrew phrase on its left.

    Defaults to the ambient Directionality, if any.
    (太字は、スクラップ作成者(matsuchiyo))

    • textAlign.startがどう解釈されるか決めるというのもよくわからない。
    • Englishの文とHebrewの文をこの順番に含んだテキストの場合、ltrにするとEnglishは左寄せ、hebrewは右寄せになる? → 次のコメントを見るとわかるけど、この記述は寄せについて言っているというよりは、ltrだったら表示される文字列のうち左にEnglishの文、右にhebrewの文が表示されるということを言っているみたい。
matsuchiyomatsuchiyo

整理してみる

  • textAlign
  • textDirection
    • 文字通り、テキストの方向。
    • 方向が異なる言語のフレーズが混じった場合に、このプロパティの効果が現れるみたい。 混じっていたら、このプロパティで指定された方向で表示される(うまく言葉にできない。上のスクショ参照)。
    • (当たり前かもしれないけど)指定されたtextDirectionとは逆のtextDirectionの言語のフレーズ内の文字の順番は変わらない。例えばFlutterは、rtlだったとしても、rettulFとなるわけではない。
    • デフォルト値は、InheritedWidgetのDirectionality(MaterialApp等の中に入っている?)によって決まる。上のスクショだとltrがデフォルトになっているように見える。
    • Android Studioなどのテキストエディタでは、ltrで表示されるみたい。
matsuchiyomatsuchiyo

今回の問い合わせに対してどうするか

  • 前提として今回、アプリの対応言語を増やすつもりはない。ヘブライ語のメモを作りたいユーザーには、アプリの言語として英語が適用される。
  • 結局、textAlignだけ、ユーザーが設定などから制御できればいい?(例えばヘブライ後のメモを作る人は、textAlignをendに設定できるようにする)
    • 基本ヘブライ語でメモをとっていて、英語が混ざってしまうと、上のスクショのendかつrtlのパターンのようになってしまう。
      • → だから、(今回修正したいメモ詳細画面の)textAlignはstart固定のままで、textDirectionをrtlに指定できるようにする。