すらぼうの開発ノート

モバイルアプリエンジニアのメモ

【Flutter】ElevatedButtonのデザイン例(サイズ、背景色、形状、枠線)

ElevatedButtonとは

api.flutter.dev

Material Designのelevated buttonを実装するウィジェット

Elevatedとは日本語で「高い」「浮き上がった」という意味。 そのためElevatedButton少し浮き上がったデザインのボタンを作成するために使用する。

実装

ElevatedButtonの実装は以下の様になっている。

  const ElevatedButton({
    super.key,
    required super.onPressed, // 一度タップされた際のイベントハンドラ
    super.onLongPress,
    super.onHover,
    super.onFocusChange,
    super.style,
    super.focusNode,
    super.autofocus = false,
    super.clipBehavior = Clip.none,
    super.statesController,
    required super.child, // ボタン上に表示するウィジェット
  });

デザインを当てるにはstyleプロパティをオーバーライドする。

デフォルトのデザイン

styleプロパティを指定しない場合、デザインは次の様になる。

ElevatedButton(onPressed: () {}, child: const Text("tap me!"))

無効時のデザイン

onPressedプロパティにnullを渡すとボタンのタップが無効になる。 デザインはグレースケールになる。

ElevatedButton(onPressed: null, child: const Text("tap me!"))

次にElevatedButtonのデザイン設定について説明する。


デザイン設定一覧

サイズ

サイズを変更する方法は2つある。

  • styleプロパティを指定
  • SizedBoxなどでラップ

styleプロパティを指定

ElevatedButtonstyleプロパティを指定することでサイズを設定できる。

ElevatedButton(
  onPressed: () {},
  child: const Text("tap me!"),
  style: ElevatedButton.styleFrom(fixedSize: Size(200, 200)), // サイズを200 x 200で指定
)

SizedBoxでラップ

SizedBoxでラップすることでサイズを設定できる。

SizedBox(
  height: 200, 
  width: 200,
  child: ElevatedButton(
    onPressed: () {},
    child: const Text("tap me!"),
  ),
)

サイズを設定する際の注意点

サイズを設定するにはConstraintsが必要。 なのでElevatedButtonContainerCenterなどでラップされる必要がある。 詳細は以下の記事を参照してほしい。

docs.flutter.dev

embrace.io

背景色

例として背景色を赤に設定する。

ElevatedButton(
  onPressed: () {},
  child: const Text("tap me!"),
  style: ElevatedButton.styleFrom(backgroundColor: Colors.red), // 背景色を赤
)

形状

Material Design 3ではElevatedButtonは角がかなり丸くなっているので、例として角を角ばらせてみる。

ElevatedButton(
  onPressed: () {},
  child: const Text("tap me!"),
  style: ElevatedButton.styleFrom(
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(0))), // 角を直角
)

枠線

枠線の色を設定する

例として枠を青く表示する。

ElevatedButton(
  onPressed: () {},
  child: const Text("tap me!"),
  style: ElevatedButton.styleFrom(
    side: BorderSide(color: Colors.blue), // 枠線を青く表示
  ),
)

枠線の太さを設定する

例として青い枠線を太くする。

ElevatedButton(
  onPressed: () {},
  child: const Text("tap me!"),
  style: ElevatedButton.styleFrom(
    side: BorderSide(color: Colors.blue, width: 10), // 幅10の青い枠線を表示
  ),
)