Convert Variable From String To Boolean In Dart
Code snippet for how to Convert Variable From String To Boolean In Dart with sample and detail explanation
In Dart, variables must be declared with a specific data type, such as String or Boolean. The type of variable sometimes needs to be converted, and this article will guide you on how to convert a variable from String to Boolean in Dart.
Code snippet for Converting Variable from String to Boolean in Dart
In our code example, we are going to consider a simple situation in which we have a String variable, and we need to convert it into a Boolean variable.
Here is a simple Dart code snippet that accomplishes this task:
void main() {
String strVar = "true";
bool boolVar = (strVar.toLowerCase() == 'true');
print(boolVar);
}
In this code, we first initialize a String variable strVar
with the value “true”. Then we convert it to a Boolean variable boolVar
and print out the result.
Code Explanation for Converting Variable from String to Boolean in Dart
Let’s break down the code snippet line by line:
-
String strVar = "true";
In this line of code, we are creating a String variable namedstrVar
and initializing it with the value “true”. -
bool boolVar = (strVar.toLowerCase() == 'true');
Here, we are creating a Boolean variable namedboolVar
. The value of this Boolean variable is determined by the whether the lower case version of the String instrVar
equals “true”. IfstrVar
is anything other than “true” (case insensitive), the resulting Boolean is ‘false’, otherwise ‘true’. -
print(boolVar);
In this line, we print out the Boolean value stored inboolVar
.
Thus, through this simple code we can convert a String to a Boolean in Dart.
Please note that this example presumes the input String will be either “true” or “false”. If other values might be present, additional validation is required.