promptWithValidation method

String promptWithValidation({
  1. String message = 'input',
  2. required String? validator(
    1. String p1
    ),
  3. Object? defaultValue,
})

Prompts the user for input with built-in validation.

Keeps asking for input until the validation passes.

Example:

final name = logger.promptWithValidation(
  message: 'Enter your name',
  validator: (input) => input.isEmpty ? 'Name cannot be empty' : null,
);

Implementation

String promptWithValidation({
  String message = 'input',
  required String? Function(String p1) validator,
  Object? defaultValue,
}) {
  while (true) {
    final result = prompt(message, defaultValue: defaultValue);

    final validatorError = validator(result);

    if (validatorError == null) {
      return result;
    }

    logger.err(validatorError);
  }
}