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

ParsingBooleanDartCoercion

Parsing Problem Overview


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

Parsing Solutions


Solution 1 - Parsing

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

Solution 2 - Parsing

No. Simply use:

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

Solution 3 - Parsing

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.

Solution 4 - Parsing

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()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioncc youngView Question on Stackoverflow
Solution 1 - ParsingGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - ParsingAlexandre ArdhuinView Answer on Stackoverflow
Solution 3 - ParsingmezoniView Answer on Stackoverflow
Solution 4 - ParsingAntonioView Answer on Stackoverflow