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:

  • int: 1 is true, 0 is false.
  • String: "true", "1", "yes" are true; "false", "0", "no" 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 int) return v == 1;
  if (v is String) {
    final s = v.toLowerCase();
    if (s == "true" || s == "1" || s == "yes") return true;
    if (s == "false" || s == "0" || s == "no") return false;
  }
  _logMismatchedType("bool", v);
  return def;
}