In Dart, is there `parse` for` bool`, as it is for `int`?

in Dart, there is a convenient way to convert a string to int:

int i = int.parse('123'); 

is there something similar for bools conversion?

 bool b = bool.parse('true'); 
+20
parsing dart coercion boolean
source share
4 answers

Bool has no methods.

 var val = 'True'; bool b = val.toLowerCase() == 'true'; 

should be simple enough.

+33
source share

Not. Just use:

 String boolAsString; bool b = boolAsString == 'true'; 
+12
source share

You cannot perform this operation as described by bool.parse('true') because the Dart SDK is as light as possible.

The Dart SDK is not as unified as, for example, the .NET Framework, where all the basic types of systems have 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 

These types also have a parse method, including a Boolean type.

Therefore, you cannot do it in a unified way. Only one.

+6
source share

I think it should be so simple.

 int a = b ? 1 : 0; 

If b is true, a will be 1. Otherwise, a will be 0.

0
source share

All Articles