promptUser function
Prompts the user for input with a default value and optional validation.
This function displays a promptMessage to the user, optionally showing
a defaultValue. It reads user input and, if the input is empty,
uses the defaultValue. The input can be validated using a validator
function, and the user will be re-prompted on invalid input.
If skip is true, the function will return skipValue (or defaultValue
if skipValue is null) without prompting the user.
promptMessage The message to display to the user.
defaultValue The default value to use if the user provides no input.
validator An optional function to validate the user's input.
skip A boolean indicating whether to skip the prompt.
skipValue An optional value to return if skip is true.
Returns the validated user input or the default/skip value.
Implementation
String promptUser(
String promptMessage,
String defaultValue, {
bool Function(String)? validator,
bool? skip,
String? skipValue,
}) {
if (skip == true) {
logger.i(
'$promptMessage >>| Skipping with (${skipValue ?? defaultValue})...',
);
return skipValue ?? defaultValue;
}
final answer = prompt(
'$promptMessage ${defaultValue.isNotEmpty ? '(Default: $defaultValue) [Enter for default]' : ''}:',
);
if (answer.isEmpty && defaultValue.isNotEmpty) {
return defaultValue;
}
if (validator != null && !validator(answer)) {
logger.e('❌ Invalid input. Please try again.');
return promptUser(promptMessage, defaultValue, validator: validator);
}
return answer;
}