LoginSignup
23
12

More than 1 year has passed since last update.

FlutterのContainerをボタンとして利用する方法

Last updated at Posted at 2020-04-01

変更履歴

2021年9月22日「GestureDetector」の章を追加。

Containerで書いていたものにタップ時の動作を追加する

これ、実はContainerのwidgetだけでは解決しませんでした。
InkWellを利用します。

〜例(前回のソースを改変)〜

home_panel.dart
        InkWell(
          onTap: () {
            showDialog(
                context: context,
                builder: (context) {
                  return AlertDialog(
                    title: Text('Aの動作の確認'),
                  );
                });
          },
          child: Container(
            padding: const EdgeInsets.all(20),
            color: Colors.grey[300],
            width: 150,
            height: 200,
            child: Center(
              child: const Text('A'),
            ),
          ),
        ),

〜〜動かした様子〜〜
onTap.gif

InkWellは「タッチに反応するマテリアルの長方形の領域」であり、
様々なWidgeに、タッチ時の動作を付与することができるようです。(任意のWidgeをまるでボタンのように使うことができる!)

公式情報
InkWell class

参考情報
https://stackoverflow.com/questions/44317188/flutter-ontap-method-for-containers/44317228
[Flutter] InkWellは意外に強い

GestureDetector

似たような用途のWidgetに「GestureDetector」があります。適宜ユースケースに合うものを選ぶようにしてください。
(後から気付いて動作確認できなかったのですが、「Containerをボタンとして利用する」だけなら「GestureDetector」でも実装可能なはずです)

公式情報
GestureDetector class

違いについては、こちらのstack overflowの回答が参考になります。
Flutter: InkWell vs GestureDetector: what is the difference?

少しここにも書くと、以下のような違いがあるそうです。

  • GestureDetectorの方が検出できるジャスチャー数が多い.
  • InkWellは検出できるジェスチャーの数が限られているが、Widgetを装飾する方法が提供されている(splashColorなど)

おまけ:ButtonのWidgetをContainerでデザインしたものに近づける場合

ButtonのWidget(例で示すのはRaisedButton)のデザインを変えて、Containerで作ったデザインに近づける場合は、ButtonThemeを使うと良さそうです。

〜例〜

home_panel.dart
        ButtonTheme(
          minWidth: 150,
          height: 200,
          padding: const EdgeInsets.all(20),
          child: RaisedButton(
            color: Colors.grey[300],
            child: const Text('B'),
            onPressed: () {
              showDialog(
                  context: context,
                  builder: (context) {
                    return AlertDialog(
                      title: Text('Bの動作の確認'),
                    );
                  });
            },
          ),
        ),

〜〜動かした様子〜〜

Bの動作.gif

公式情報
ButtonTheme class

参考情報
https://stackoverflow.com/questions/50293503/how-to-set-the-width-of-a-raisedbutton-in-flutter

AとB、見た目も動作もほぼほぼ同じに見えますね。

〜〜違い〜〜
RaisedButtonの方が少し浮き上がっていたり、
onTaponPressedで挙動が少々異なったりはしています。
(gif画像だとわかりにくいかもしれません)
またInkWellの方ではonPressedは用意されていないようです。
使い分けるなら、上記のような話でしょうか。

またInkWellでハイライト(highlightColoronHighlightChanged)しようとしましたが、うまく行きませんでした。(用意はされています)ハイライトやるならRaisedButtonの方が簡単そうです。

以上です!

23
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
12