[Flutter]ElevatedButtonの無効時の色を設定する方法

Flutter

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

ElevatedButtonの無効時の色を設定する方法を紹介します。

スポンサーリンク

方法

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

ElevatedButtonのタップが無効になっている時の色を設定するには、ButtonStyleを使います。

ButtonStyleのbackgroundColor(背景色)とforegroundColor(テキストの色)をそれぞれ条件分岐で変化させます。

ElevatedButton(
              onPressed: null,
              child: Text('Submit disable'),
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.resolveWith<Color>(
                  (Set<MaterialState> states) {
                    if (states.contains(MaterialState.disabled))
                      return Colors.green; //無効時の色
                    return Colors.blue; // デフォルトカラー
                  },
                ),
              ),
            )

MaterialStateProperty.resolveWithでは、ボタンの状態によって条件分岐をすることが出来ます。

また、foregroundColorでテキストの色を設定する場合も同様にします。

もし、無効かどうかを変数で指定しているならば、三項演算子で簡単に条件分岐させる方法もあります。

bool isDisabled = false;

・・・

ElevatedButton(
              onPressed: () {},
              child: Text('有効'),
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(
                    isDisabled ? Colors.green : Colors.blue),
              ),
            )

まとめ

ElevatedButtonの無効時の色を設定するには、ButtonStyleのbackgroundColorで条件分岐をします。

コメント

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