text method
Asks for a line of text.
Returns defaultValue when the user just presses enter. Re-asks while the
answer is empty and no default exists.
validate returns an error message to reject an answer, or null to accept
it. Rejecting here rather than after the last question is the difference
between retyping one field and retyping the whole wizard.
Implementation
String text(
String question, {
String? defaultValue,
bool allowEmpty = false,
String? Function(String)? validate,
}) {
while (true) {
final hint = defaultValue == null || defaultValue.isEmpty
? ''
: ' ${ColorizeLogger.dim('($defaultValue)')}';
stdout.write('${ColorizeLogger.bold('?')} $question$hint ');
final typed = _readLine().trim();
final String answer;
if (typed.isNotEmpty) {
answer = typed;
} else if (defaultValue != null && defaultValue.isNotEmpty) {
answer = defaultValue;
} else if (allowEmpty) {
// `allowEmpty` says nothing is a valid answer, so there is nothing for
// [validate] to judge — running it here would let the two options
// contradict each other.
return '';
} else {
_logger.logWarning('a value is required');
continue;
}
final problem = validate?.call(answer);
if (problem == null) return answer;
_logger.logWarning(problem);
}
}