Containerで書いていたものにタップ時の動作を追加する
これ、実はContainer
のwidgetだけでは解決しませんでした。
InkWell
を利用します。
〜例(前回のソースを改変)〜
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'),
),
),
),
InkWell
は「タッチに反応するマテリアルの長方形の領域」であり、
様々なWidgeに、タッチ時の動作を付与することができるようです。(任意のWidgeをまるでボタンのように使うことができる!)
公式情報
InkWell class
参考情報
https://stackoverflow.com/questions/44317188/flutter-ontap-method-for-containers/44317228
[Flutter] InkWellは意外に強い
おまけ:ButtonのWidgetをContainerでデザインしたものに近づける場合
ButtonのWidget(例で示すのはRaisedButton
)のデザインを変えて、Container
で作ったデザインに近づける場合は、ButtonTheme
を使うと良さそうです。
〜例〜
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の動作の確認'),
);
});
},
),
),
〜〜動かした様子〜〜
公式情報
ButtonTheme class
参考情報
https://stackoverflow.com/questions/50293503/how-to-set-the-width-of-a-raisedbutton-in-flutter
AとB、見た目も動作もほぼほぼ同じに見えますね。
〜〜違い〜〜
RaisedButton
の方が少し浮き上がっていたり、
onTap
とonPressed
で挙動が少々異なったりはしています。
(gif画像だとわかりにくいかもしれません)
またInkWell
の方ではonPressed
は用意されていないようです。
使い分けるなら、上記のような話でしょうか。
またInkWell
でハイライト(highlightColor
とonHighlightChanged
)しようとしましたが、うまく行きませんでした。(用意はされています)ハイライトやるならRaisedButton
の方が簡単そうです。
以上です!
コメント