[Flutter]TextFormFieldのラベルの色をフォーカスで変えるには?

Flutter

どうも、ちょげ(@chogetarou)です。

TextFormFieldのラベルの色をフォーカス(入力中)で変える方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

TextFormFieldのラベルの色をフォーカスで変えるには、Focusウェジェットを使います。

まず、フォーカス中かどうかを判断する変数を用意します。

  var _isFocus = false;

次に、TextFormFieldをFocusでラップします。

そして、Focusの引数「onFocusChange」で、用意した変数の値を変更します。

Focus(
  onFocusChange: (isFocus) {
    setState(() {
      _isFocus = isFocus;
    });
  },
  child: TextFormField(・・・),
),

最後に、InputDecorationの引数「labelStyle」に指定しているラベルの色を、用意した変数によって切り替わるようにします。

TextFormField(
  decoration: InputDecoration(
    labelText: 'ラベル',
    labelStyle: TextStyle(
      color: _isFocus ? /*フォーカス時の色*/: /*通常時の色*/,
    ),
  ),
),

これでTextFormFieldのラベルの色をフォーカスで変えることが出来ます。

使用例

以下は、使用例です。

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  var _isFocus = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Focus(
            onFocusChange: (isFocus) {
              setState(() {
                _isFocus = isFocus;
              });
            },
            child: TextFormField(
              decoration: InputDecoration(
                labelText: 'Name',
                labelStyle: TextStyle(
                  color: _isFocus ? Colors.pink : Colors.grey,
                ),
                border: OutlineInputBorder(),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

コメント

タイトルとURLをコピーしました