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

cc young picture cc young · Jan 15, 2014 · Viewed 38.5k times · Source

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');

Answer

Günter Zöchbauer picture Günter Zöchbauer · Jan 15, 2014

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