confirm function

bool confirm(
  1. String prompt, {
  2. bool? defaultValue,
  3. CustomConfirmPrompt customPrompt = Confirm.defaultPrompt,
})

confirm is a specialized version of ask that returns true or false based on the value entered.

The user must enter a valid value or, if a defaultValue is passed, the enter key.

Accepted values are y|t|true|yes and n|f|false|no (case insenstiive).

If the user enters an unknown value an error is printed and they are reprompted.

The prompt is displayed to the user with ' (y/n)' appended.

If a defaultValue is passed then either the y or n will be capitalised and if the user hits the enter key then the defaultValue will be returned.

If the script is not attached to a terminal Terminal().hasTerminal then confirm returns immediately with the defaultValue. If there is no defaultValue then true is returned.

Implementation

bool confirm(String prompt,
    {bool? defaultValue,
    CustomConfirmPrompt customPrompt = Confirm.defaultPrompt}) {
  var result = false;
  var matched = false;

  if (!Terminal().hasTerminal) {
    return defaultValue ?? true;
  }

  while (!matched) {
    final entered = ask(
      prompt,
      toLower: true,
      required: false,
      customPrompt: (_, __, ___) => customPrompt(prompt, defaultValue),
    );
    var lower = entered.trim().toLowerCase();

    if (lower.isEmpty && defaultValue != null) {
      lower = defaultValue ? 'true' : 'false';
    }

    if (['y', 't', 'true', 'yes'].contains(lower)) {
      result = true;
      matched = true;
      break;
    }
    if (['n', 'f', 'false', 'no'].contains(lower)) {
      result = false;
      matched = true;
      break;
    }
    print('Invalid value: $entered');
  }
  return result;
}