in Dart, there's a convenient way to convert a String to an int:
int i = int.parse('123');
is there something similar for converting bools?
bool b = bool.parse('true');
There is no way to automatically "convert" an integer to a boolean. Dart objects have a type, and converting them to a different type would mean changing which object they are, and that's something the language have chosen not to do for you. The condition needs to be a boolean, and an integer is-not a boolean.
Converts the specified string representation of a logical value to its Boolean equivalent.
In Dart splitting of a string can be done with the help split string function in the dart. It is a built-in function use to split the string into substring across a common character. This function splits the string into substring across the given pattern and then store them to a list.
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.'; } }
No. Simply use:
String boolAsString; bool b = boolAsString == 'true';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With