date static method

DateTime? date({
  1. required String title,
  2. DateTime? defaultValue,
  3. DateTime? min,
  4. DateTime? max,
  5. bool returnDefaultOnEndOfInput = true,
})

Reads a strict ISO calendar date (YYYY-MM-DD).

Implementation

static DateTime? date({
  required String title,
  DateTime? defaultValue,
  DateTime? min,
  DateTime? max,
  bool returnDefaultOnEndOfInput = true,
}) {
  final normalizedDefault = defaultValue == null
      ? null
      : DateTime(defaultValue.year, defaultValue.month, defaultValue.day);
  while (true) {
    _writePrompt(title,
        defaultValue: normalizedDefault == null
            ? null
            : _formatDate(normalizedDefault));
    final line = TerminalContext.input.readLineSync();
    if (line == null) {
      return returnDefaultOnEndOfInput ? normalizedDefault : null;
    }
    final text = line.trim();
    if (text.isEmpty && normalizedDefault != null) return normalizedDefault;
    final value = _parseDate(text);
    if (value == null) {
      _writeError('Enter a real date as YYYY-MM-DD.');
      continue;
    }
    if (min != null &&
        value.isBefore(DateTime(min.year, min.month, min.day))) {
      _writeError('Enter a date on or after ${_formatDate(min)}.');
      continue;
    }
    if (max != null &&
        value.isAfter(DateTime(max.year, max.month, max.day))) {
      _writeError('Enter a date on or before ${_formatDate(max)}.');
      continue;
    }
    return value;
  }
}