showDateTimePicker function

Future<DateTime?> showDateTimePicker({
  1. required BuildContext context,
  2. DateTime? initialDate,
  3. DateTime? firstDate,
  4. DateTime? lastDate,
})

Implementation

Future<DateTime?> showDateTimePicker(
    {required BuildContext context,
    DateTime? initialDate,
    DateTime? firstDate,
    DateTime? lastDate}) async {
  initialDate ??= DateTime.now();
  firstDate ??= initialDate.subtract(const Duration(days: 365 * 100));
  lastDate ??= firstDate.add(const Duration(days: 365 * 200));

  final DateTime? selectedDate = await showDatePicker(
    context: context,
    initialDate: initialDate,
    firstDate: firstDate,
    lastDate: lastDate,
  );

  if (selectedDate == null) {
    return null;
  }

  if (!context.mounted) {
    // Check if the widget is alive
    return selectedDate;
  }

  final TimeOfDay? selectedTime = await showTimePicker(
    context: context,
    initialTime: TimeOfDay.fromDateTime(initialDate),
  );

  if (selectedTime == null) {
    return selectedDate;
  } else {
    return DateTime(
      selectedDate.year,
      selectedDate.month,
      selectedDate.day,
      selectedTime.hour,
      selectedTime.minute,
    );
  }
}