parseBool static method

bool? parseBool(
  1. Object? value, [
  2. bool? def
])

Tries to parse a bool.

  • Returns def if value is invalid.

Implementation

static bool? parseBool(Object? value, [bool? def]) {
  if (value == null) return def;

  if (value is bool) {
    return value;
  } else if (value is num) {
    return value > 0;
  } else {
    var s = _valueAsString(value).toLowerCase();
    if (s.isEmpty || s == 'null' || s == 'empty') return def;

    if (s == 'true' ||
        s == 't' ||
        s == 'yes' ||
        s == 'y' ||
        s == '1' ||
        s == '+' ||
        s == 'ok') {
      return true;
    }

    if (s == 'false' ||
        s == 'f' ||
        s == 'no' ||
        s == 'n' ||
        s == '0' ||
        s == '-1' ||
        s == '-' ||
        s == 'fail' ||
        s == 'error' ||
        s == 'err') {
      return false;
    }

    var n = _parseNumString(value);
    if (n != null) {
      return n > 0;
    }

    return def;
  }
}