関数やWidgetを作るとき、「この引数は絶対に必要!」と指定できます。
普通の書き方:
// どれも省略可能
void showMessage(String title, String message, String buttonText) {
print('$title: $message');
}
// 呼び出し - 全部書かないとエラー
showMessage('警告', 'データがありません', 'OK');
でも、どれが必須でどれが省略可能か分かりにくい…プログラムを実行したときに値が決まる
required を使った書き方:
void showMessage({
required String title, // 必須!
required String message, // 必須!
String buttonText = 'OK', // 省略可能(デフォルト値あり)
}) {
print('$title: $message');
}
// 呼び出し
showMessage(
title: '警告',
message: 'データがありません',
// buttonText は省略してもOK
);
メリット: 必須項目を忘れると、エディタがエラーで教えてくれる!
Flutter の Widget で超よく使う:
class StudentCard extends StatelessWidget {
final String name; // これは必須
final int fee; // これも必須
final bool isPaid; // これも必須
const StudentCard({
Key? key,
required this.name, // 必須パラメータ
required this.fee, // 必須パラメータ
required this.isPaid, // 必須パラメータ
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Card(
child: Text('$name: $fee円'),
);
}
}
// 使うとき
StudentCard(
name: '田中太郎', // これを忘れるとエラー!
fee: 8000, // これも忘れるとエラー!
isPaid: true, // これも!
)
required がないと起こる問題:
// required なし
class MyWidget extends StatelessWidget {
final String? title; // null許容にするしかない
const MyWidget({this.title});
@override
Widget build(BuildContext context) {
return Text(title ?? ''); // null チェックが必要...
}
}
問題点: 値が渡されないかもしれない → いつも null チェック必要
// required あり
class MyWidget extends StatelessWidget {
final String title; // 絶対にある!
const MyWidget({required this.title});
@override
Widget build(BuildContext context) {
return Text(title); // null チェック不要!
}
}
必須とオプションを組み合わせ:
class EventCard extends StatelessWidget {
final String eventName; // 必須
final DateTime eventDate; // 必須
final String? location; // 省略可能
final String description; // 必須
const EventCard({
Key? key,
required this.eventName,
required this.eventDate,
this.location, // required なし = 省略可能
required this.description,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Card(
child: Column(
children: [
Text(eventName),
Text('${eventDate.month}月${eventDate.day}日'),
if (location != null) Text('会場: $location'), // あれば表示
Text(description),
],
),
);
}
}
まとめ
required を付けると「これは絶対に必要!」と明示できて、忘れるとエラーで教えてくれます! バグ予防に超便利!
