toBool function

IValidator toBool(
  1. IValidator child, {
  2. String? message,
})

Coerces a value to a boolean (standard mode).

Accepted inputs (case-insensitive):

  • bool values (true, false)
  • Integers: 1 => true, 0 => false
  • Strings: "true", "false"

This is intentionally stricter than toBoolLenient (which also accepts yes/no, y/n, on/off, t/f, 1/0 string variants) while still allowing the common numeric toggles via int type. Use toBoolStrict if you need ONLY literal true/false (and bools) and want to reject 1/0 entirely.

See also:

Implementation

IValidator toBool(IValidator child, {String? message}) {
  final validator =
      (($isBool | isOneOf([0, 1]) | toLowerCase(isString() & isOneOf(['true', 'false'])))) &
          core.transform((v) {
            return switch (v) {
              final bool b => b,
              final int i => i == 1,
              final String s => s.toLowerCase().trim() == 'true',
              _ => null,
            };
          }, child);

  return handleReturnPreserveValue(validator, message);
}