こちらのボタン普通に書くと...
テキストだけ変更してあり、他は同じ内容のコードが書いてあります。
main.dart
body: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24), // 左右に24pxの余白
child: Column(
mainAxisAlignment: MainAxisAlignment.center, // 画面の中央に配置
children: <Widget>[
// Loginボタン
SizedBox(
width: double.infinity, // ボタンの横幅をいっぱいにする
height: 56, // ボタンの高さを56pxにする
child: ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
backgroundColor: const Color.fromRGBO(136, 125, 255, 1)), // ボタンの背景色
child: const Text(
'Login',
style: TextStyle( // ボタンの中のテキストのカラー・サイズ
color: Colors.white,
fontSize: 24,
),
),
),
),
// 2つのボタンの間の余白
SizedBox(
height: 24,
),
// Sign Upボタン
SizedBox(
width: double.infinity, // ボタンの横幅をいっぱいにする
height: 56.0, // ボタンの高さを56pxにする
child: ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
backgroundColor: const Color.fromRGBO(136, 125, 255, 1)), // ボタンの背景色
child: const Text(
'Sign Up',
style: TextStyle( // ボタンの中のテキストのカラー・サイズ
color: Colors.white,
fontSize: 24,
),
),
),
),
],
),
),
),
なのでクラスを使ってデザインを使いまわします!!
任意の名前で新しいファイル(button_widget.dart)を作成します。
lib
├ main.dart
└ button_widget.dart
新しいファイル内でwidgetを作成します。(stlでショートカットしてます)
stlはStateless Widgetを作成できます。stfでStatefull Widgetを作成できます。
使いまわしたい部分をコピーしreturnの後に貼り付けます。
テキストだけは変更可能にしたいので変数を用意しました。
なので、Textの値をlabelに変更しています。
button_widget.dart
import 'package:flutter/material.dart';
class ButtonWidget extends StatelessWidget {
final String label; // ボタンに表示するテキストを格納するための変数
const ButtonWidget({super.key, required this.label, required Null Function() onPressed});
@override
Widget build(BuildContext context) {
return SizedBox(
width: double.infinity, // 横幅をいっぱいにする
height: 56.0, // 高さを56pxにする
child: ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
backgroundColor: const Color.fromRGBO(136, 125, 255, 1)), // ボタンの背景色
child: Text(
label,
style: TextStyle( // ボタンの中のテキストのカラー・サイズ
color: Colors.white,
fontSize: 24,
),
),
),
);
}
}
main.dartで作成したクラスを使用します
body: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24), // 左右に24pxの余白
child: Column(
mainAxisAlignment: MainAxisAlignment.center, // 中央に配置
children: <Widget>[
// Loginボタン
ButtonWidget(label: 'Login', onPressed: () {}),
// 2つのボタンの間の余白
const SizedBox(
height: 24,
),
// Sign Upボタン
ButtonWidget(label: 'Sign Up', onPressed: () {}),
],
),
),
),
コードが短くなりました!よく使い回すデザインはコンポーネント化するとコードの再利用性と保守性が向上するので意識していこうと思います。
Flutterでコンポーネント化の第一歩として書かせていただきました。これからもFlutterの学習を進めていきます。