我有注册表,我想验证年龄只允许18岁。
IconButton(
icon: Icon(
color: Colors.grey[250],
Icons.calendar_month_outlined),
onPressed: () async {
DateTime? pickedDate = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(1930),
lastDate: DateTime.now());
setState(() => pickedDate = pickedDate);
if (pickedDate != null) {
_dateOfBirth.text = pickedDate.toString().substring(0, 10);
}
},
),
我有这个日期选择器,请告诉我如何验证所选日期是否有效(18 岁)。
您已在
isBefore
中与 DateTime
进行核对。
bool isAdult(DateTime date) {
final DateTime today = DateTime.now();
final DateTime adultDate = DateTime(
date.year + 18,
date.month,
date.day,
);
return adultDate.isBefore(today);
}