toBool function
Coerces a value to a boolean (standard mode).
Accepted inputs (case-insensitive):
boolvalues (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:
- toBoolStrict – strict literal parsing only
- toBoolLenient – permissive parsing of many textual toggles
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);
}