askString static method

Future<String> askString(
  1. String question, {
  2. String? defaultValue,
  3. bool validator(
    1. String
    )?,
  4. String? validationMessage,
  5. String? fromStep,
})

Drop-in replacement for UserPrompt.askString that throws BackNavigation when the user types one of backKeywords and CancelNavigation when the user types one of cancelKeywords.

The validator (if any) is bypassed for the back/cancel keywords so the user can always retreat regardless of what the prompt expects.

Implementation

static Future<String> askString(
  String question, {
  String? defaultValue,
  bool Function(String)? validator,
  String? validationMessage,
  String? fromStep,
}) async {
  while (true) {
    final String result = await UserPrompt.askString(
      '$question  (or "back")',
      defaultValue: defaultValue,
      validator: (String s) {
        // Always allow back/cancel keywords through validation.
        final String lower = s.trim().toLowerCase();
        if (backKeywords.contains(lower) ||
            cancelKeywords.contains(lower)) {
          return true;
        }
        return validator?.call(s) ?? true;
      },
      validationMessage: validationMessage,
    );

    final String trimmed = result.trim();
    final String lower = trimmed.toLowerCase();

    if (backKeywords.contains(lower)) {
      throw BackNavigation(fromStep: fromStep);
    }
    if (cancelKeywords.contains(lower)) {
      throw CancelNavigation(reason: 'user typed "$trimmed"');
    }
    return result;
  }
}