はじめに
ある仕事でFlutterまがいのことをしています。その過程でCardウィジェット上にボタンウィジェットを配置していたところを、Card自体をボタンにできないかと指示を受けました。
Flutter界隈ではもう当然のことなのかもしれませんが、自分は調べてもそれらしいものも出てこず閃くまで時間がかかったので備忘録的に残しておきます。
※記事内コードはすべてC#です。
どうするの
最初に結論書いてしまいますが、RaisedButtonウィジェットを使えばいいだけです!
実はこの二つには共通するコンストラクタの引数が多いのです。というかデザイン周りはほとんど一緒で、Cardにある引数はほぼ全てRaisedButtonも保有しています。以下実装されているコードからコンストラクタのみ抜粋。
public Card(
Key key = null,
Color color = null,
float? elevation = null,
ShapeBorder shape = null,
bool borderOnForeground = true,
EdgeInsets margin = null,
Clip? clipBehavior = null,
Widget child = null) : base(key: key) {
D.assert(elevation == null || elevation >= 0.0f);
this.color = color;
this.elevation = elevation;
this.shape = shape;
this.borderOnForeground = borderOnForeground;
this.margin = margin;
this.clipBehavior = clipBehavior;
this.child = child;
}
public RaisedButton(
Key key = null,
VoidCallback onPressed = null,
ValueChanged<bool> onHighlightChanged = null,
ButtonTextTheme? textTheme = null,
Color textColor = null,
Color disabledTextColor = null,
Color color = null,
Color disabledColor = null,
Color highlightColor = null,
Color splashColor = null,
Brightness? colorBrightness = null,
float? elevation = null,
float? highlightElevation = null,
float? disabledElevation = null,
EdgeInsets padding = null,
ShapeBorder shape = null,
Clip? clipBehavior = Clip.none,
MaterialTapTargetSize? materialTapTargetSize = null,
TimeSpan? animationDuration = null,
Widget child = null
) : base(
key: key,
onPressed: onPressed,
onHighlightChanged: onHighlightChanged,
textTheme: textTheme,
textColor: textColor,
disabledTextColor: disabledTextColor,
color: color,
disabledColor: disabledColor,
highlightColor: highlightColor,
splashColor: splashColor,
colorBrightness: colorBrightness,
elevation: elevation,
highlightElevation: highlightElevation,
disabledElevation: disabledElevation,
padding: padding,
shape: shape,
clipBehavior: clipBehavior,
materialTapTargetSize: materialTapTargetSize,
animationDuration: animationDuration,
child: child) {
D.assert(elevation == null || elevation >= 0.0);
D.assert(highlightElevation == null || highlightElevation >= 0.0);
D.assert(disabledElevation == null || disabledElevation >= 0.0);
}
なので、Cardウィジェット自体(全体)をボタンとして扱いたいと思ったときはRaisedButtonを用いてあげればOKということです。
以下は同じ見た目になるようにしたRaisedButtonとCardです。
MyRaisedButton.cs
new RaisedButton(
color: Colors.white,
clipBehavior: Clip.antiAlias,
shape: AppController.instance.GameCardDesign.CreateShape(),
child: new Container(
margin: EdgeInsets.all(2),
child: content
),
onPressed: (() => OnTap(context))
);
MyCard.cs
new Card(
color: Colors.white,
clipBehavior: Clip.antiAlias,
shape: AppController.instance.GameCardDesign.CreateShape(),
child: new Container(
margin: EdgeInsets.all(2),
child: content
)
);
いや、わかってしまうとあまりにもあっけなさすぎて、この記事の内容も薄すぎて泣きたくなってくる。。。