如何在 Flutter 中验证日期是否是 X 年前

问题描述 投票:0回答:1

我有注册表,我想验证年龄只允许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 岁)。

flutter datetime
1个回答
2
投票

您已在

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.