toBoolOrNull method

bool? toBoolOrNull()

Parses common truthy/falsy strings into a bool, or null if unknown.

Recognizes (case-insensitively) true/false, yes/no, 1/0, and on/off.

Example:

'Yes'.toBoolOrNull(); // true
'0'.toBoolOrNull(); // false
'maybe'.toBoolOrNull(); // null

Implementation

bool? toBoolOrNull() {
  switch (trim().toLowerCase()) {
    case 'true':
    case 'yes':
    case '1':
    case 'on':
      return true;
    case 'false':
    case 'no':
    case '0':
    case 'off':
      return false;
    default:
      return null;
  }
}