FlutterのTextのtextAlignとtextDirectionの違い
- 日本語と英語に対応したメモアプリを出している。
- 今回、あるユーザーからヘブライ語のように右から左に書く言語のメモでは、メモの本文を左寄せではなく、右寄せにして欲しいと問い合わせをもらった。
- そこでFlutterのText周りを調べていたところ、今回使いそうなものとして、textAlignとtextDirectionがあった。
- この違いがよくわからないので、スクラップとして残す。
まず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.
- テキストをコンテナの先頭に揃える。先頭は、TextDirection.ltrなら左、rtlなら右になる。
-
TextAlign enum
次に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の文が表示されるということを言っているみたい。
動かしてみた

整理してみる
- textAlign
- エリア内での文字列の配置。この辺の説明がわかりやすかった↓。
textAlign aligns the text in the space occupied by Text when that occupied space is bigger than the actual content.
https://stackoverflow.com/questions/51638176/under-which-circumstances-textalign-property-works-in-flutter - TextAlign.start(とend)は、textDirectionの値によって振る舞いが変わる。
- textDirectionが、ltrなら、右寄せ。
- textDirectionが、rtlなら、左寄せ。
- デフォルト値は、start?ドキュメントに記載が見当たらなかった: textAlign property
- エリア内での文字列の配置。この辺の説明がわかりやすかった↓。
- textDirection
- 文字通り、テキストの方向。
- 方向が異なる言語のフレーズが混じった場合に、このプロパティの効果が現れるみたい。 混じっていたら、このプロパティで指定された方向で表示される(うまく言葉にできない。上のスクショ参照)。
- (当たり前かもしれないけど)指定されたtextDirectionとは逆のtextDirectionの言語のフレーズ内の文字の順番は変わらない。例えばFlutterは、rtlだったとしても、rettulFとなるわけではない。
- デフォルト値は、InheritedWidgetのDirectionality(MaterialApp等の中に入っている?)によって決まる。上のスクショだとltrがデフォルトになっているように見える。
- Android Studioなどのテキストエディタでは、ltrで表示されるみたい。
今回の問い合わせに対してどうするか
- 前提として今回、アプリの対応言語を増やすつもりはない。ヘブライ語のメモを作りたいユーザーには、アプリの言語として英語が適用される。
- 結局、textAlignだけ、ユーザーが設定などから制御できればいい?(例えばヘブライ後のメモを作る人は、textAlignをendに設定できるようにする)
- 基本ヘブライ語でメモをとっていて、英語が混ざってしまうと、上のスクショのendかつrtlのパターンのようになってしまう。
- → だから、(今回修正したいメモ詳細画面の)textAlignはstart固定のままで、textDirectionをrtlに指定できるようにする。
- 基本ヘブライ語でメモをとっていて、英語が混ざってしまうと、上のスクショのendかつrtlのパターンのようになってしまう。