boolVal static method

bool boolVal(
  1. dynamic v, {
  2. bool def = false,
})

Safely converts a dynamic value v to bool.

Returns def if the value is null or unrecognizable.

Recognizes:

  • num: non-zero is true, 0 is false.
  • String: "true", "1", "yes", "t", "on" are true; "false", "0", "no", "f", "off" are false.

Example:

JsonCare.boolVal("yes"); // true
JsonCare.boolVal(1);     // true

Implementation

static bool boolVal(dynamic v, {bool def = false}) {
  if (v == null) return def;
  if (v is bool) return v;
  if (v is num) return v != 0;
  if (v is String) {
    final s = v.trim().toLowerCase();
    if (s == "true" || s == "1" || s == "yes" || s == "t" || s == "on") {
      return true;
    }
    if (s == "false" || s == "0" || s == "no" || s == "f" || s == "off") {
      return false;
    }
  }
  _logMismatchedType("bool", v);
  return def;
}