Is there a parsing of bool like int in Dart?

boolean, dart, string

Solution

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.';
  }
}

Problem

In `Dart`, there is a convenience method for converting a `String` to an `int`: ``` int i = int.parse('123'); ``` Is there something similar for converting `String` to `bool`? ``` bool b = bool.parse('true'); ```

Original source