FlutterのTextFieldのラベルを常に上部表示にしたり位置を変えたりする
やりたいこと
以下を実現したい場合のFlutter側の実装を紹介する。
- TextFieldにフォーカスが当たってなくてもラベルを上部に表示させる
- ラベル位置を変える
以下のようなUIを組むことができる。

ラベルを上部に表示させる
InputDecorationクラスのfloatingLabelBehaviorプロパティにFloatingLabelBehavior.alwaysを指定することで実現できる。
const TextField(
decoration: InputDecoration(
floatingLabelBehavior: FloatingLabelBehavior.always,
labelText: 'Label Name 1',
hintText: 'Hint Text 1',
hintStyle: TextStyle(color: Colors.grey),
border: OutlineInputBorder(),
),
),
FloatingLabelBehaviorはenumであり、他の値としてはデフォルトのautoやneverがある。
ラベル位置を変える
InputDecorationクラスのfloatingLabelAlignmentプロパティにFloatingLabelAlignment.centerを指定することで実現できる。
const TextField(
decoration: InputDecoration(
floatingLabelAlignment: FloatingLabelAlignment.center,
labelText: 'Label Name 2',
hintText: 'Hint Text 2',
hintStyle: TextStyle(color: Colors.grey),
border: OutlineInputBorder(),
),
),
FloatingLabelAlignmentはenumではないが、定数にcenterとstartがあるのでenumっぽく使うことができる。