Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Dart, is there a `parse` for `bool` as there is for `int`?

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'); 
like image 488
cc young Avatar asked Jan 15 '14 09:01

cc young


People also ask

How do you convert int to bool in darts?

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.

What does bool parse do?

Converts the specified string representation of a logical value to its Boolean equivalent.

How do you parse a Dart string?

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.


2 Answers

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.';   } } 
like image 148
Günter Zöchbauer Avatar answered Sep 25 '22 17:09

Günter Zöchbauer


No. Simply use:

String boolAsString; bool b = boolAsString == 'true'; 
like image 35
Alexandre Ardhuin Avatar answered Sep 24 '22 17:09

Alexandre Ardhuin