【Flutter】ボタンウィジェット
ボタンの種類
Flutter には以下の 3 種類のボタンウィジェットがあります。 プロパティなどは同じで、ボタンの見た目が異なります。
| ウィジェット | 影 | 外線 |
|---|---|---|
TextButton | - | - |
ElevatedButton | ● | - |
OutlinedButton | - | ● |
TextButton(
child: Text('TextButton'),
onPressed: () => print('clicked!'),
)ElevatedButton(
child: Text('ElevatedButton'),
onPressed: () => print('clicked!'),
)OutlinedButton(
child: Text('OutlinedButton'),
onPressed: () => print('clicked!'),
)ボタンウィジェットでは、childとonPressedが必須のプロパティとなります。
childには、テキストやアイコンなどを設定します。
onPressedは、ボタンを押した場合の処理を設定します。
以下のようにnullを設定すると、disabled となり、ボタンの見た目も変わります。
TextButton(
child: Text('TextButton'),
onPressed: null,
)ボタンのスタイル
ボタンのスタイルはstyleプロパティに、各ボタンウィジェットのstyleFrom()メソッドを使用します。
TextButton(
child: Text('TextButton'),
onPressed: () => print('clicked!'),
style: TextButton.styleFrom(
//...
),
)色
ボタンの色はprimaryプロパティを設定します。
TextButtonとOutlinedButtonでは、テキストとアイコンの色、ホバー、フォーカス、押された際のアニメーションの色が設定されます。
TextButton(
child: Text('TextButton'),
onPressed: () => print('clicked!'),
style: TextButton.styleFrom(
primary: Colors.red,
),
)ElevatedButtonでは、primaryプロパティでにより背景色が設定できます。
テキストなどの色は、onPrimaryプロパティで設定します。
ElevatedButton(
child: Text('ElevatedButton'),
onPressed: () => print('clicked!'),
style: TextButton.styleFrom(
primary: Colors.red,
onPrimary: Colors.yellow,
shadowColor: Colors.yellow,
),
)また disabled 時の色をonSurfaceプロパティにより設定できます。
TextButton(
child: Text('TextButton'),
onPressed: null,
style: TextButton.styleFrom(
onSurface: Colors.red
),
)影
ElevatedButtonでは、shadowColorで影の色を、elevationで影の大きさを設定します。
ElevatedButton(
child: Text('ElevatedButton'),
onPressed: () => print('clicked!'),
style: TextButton.styleFrom(
shadowColor: Colors.red,
elevation: 5.0,
),
)サイズ・位置
ボタンの大きさはfixedSizeまたはminimamSizeプロパティで設定します。
fixedSizeは固定値、minimamSizeは最小値を設定します。
またalignmentによって子ウィジェットの位置を設定でき、paddingによって中の余白を設定できます。
TextButton(
child: Text('TextButton'),
onPressed: () => print('clicked!'),
style: TextButton.styleFrom(
fixedSize: Size(100, 100),
alignment: Alignment.topLeft,
padding: EdgeInsets.all(10),
),
)線
線の色や太さは、sideプロパティで設定します。
OutlinedButton(
child: Text('OutlinedButton'),
onPressed: () => print('clicked!'),
side: BorderSide(
color: Colors.red,
width: 3.0,
),
)形状
ボタンの形状は、shapeプロパティ以下のクラスを設定することで変化させることができます。
BeveledRectangleBordershape: BeveledRectangleBorder( borderRadius: BorderRadius.circular(10), ),CircleBordershape: CircleBorder(),ContinuousRectangleBordershape: ContinuousRectangleBorder( borderRadius: BorderRadius.circular(10), ),RoundedRectangleBordershape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ),StadiumBordershape: StadiumBorder(),
アイコン
アイコンを使用する場合は、icon()を使用します。
childプロパティの代わりに、labelプロパティにテキストを、iconプロパティにアイコンを設定します。
TextButton.icon(
label: Text('TextButton'),
icon: Icon(Icons.favorite),
onPressed: () => print('clicked!'),
)