Question

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');
Was it helpful?

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

OTHER TIPS

No. Simply use:

String boolAsString;
bool b = boolAsString == 'true';

You cannot perform this operation as you describe bool.parse('true') because Dart SDK is a lightweight as possible.

Dart SDK is not so unified as, for example, NET Framework where all basic system types has the following unification.

IConvertible.ToBoolean
IConvertible.ToByte
IConvertible.ToChar
IConvertible.ToDateTime
IConvertible.ToDecimal
IConvertible.ToDouble
IConvertible.ToInt16
IConvertible.ToInt32
IConvertible.ToInt64
IConvertible.ToSByte
IConvertible.ToSingle
IConvertible.ToString
IConvertible.ToUInt16
IConvertible.ToUInt32
IConvertible.ToUInt64

Also these types has parse method, including Boolean type.

So you cannot to do this in unified way. Only by yourself.

Actually yes, there is!

It's as simple as

bool.fromEnvironment(strValue, defaultValue: defaultValue);

Keep in mind that you may need to do strValue.toLowerCase()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top