in Dart, is there a `parse` for `bool` as there is for `int`?
No. Simply use:
String boolAsString;
bool b = boolAsString == 'true';
Bool has no methods.
var val = 'True';
bool b = val.toLowerCase() == 'true';
should be easy enough.
With recent Dart versions with extension method support the code could be made look more like for int
, num
, float
.
extension BoolParsing on String {
bool parseBool() {
return this.toLowerCase() == 'true';
}
}
void main() {
bool b = 'tRuE'.parseBool();
print('${b.runtimeType} - $b');
}
See also https://dart.dev/guides/language/extension-methods
To the comment from @remonh87
If you want exact 'false'
parsing you can use
extension BoolParsing on String {
bool parseBool() {
if (this.toLowerCase() == 'true') {
return true;
} else if (this.toLowerCase() == 'false') {
return false;
}
throw '"$this" can not be parsed to boolean.';
}
}