OneBite.Dev - Coding blog in a bite size

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:

  1. String strVar = "true";
    In this line of code, we are creating a String variable named strVar and initializing it with the value “true”.

  2. bool boolVar = (strVar.toLowerCase() == 'true');
    Here, we are creating a Boolean variable named boolVar. The value of this Boolean variable is determined by the whether the lower case version of the String in strVar equals “true”. If strVar is anything other than “true” (case insensitive), the resulting Boolean is ‘false’, otherwise ‘true’.

  3. print(boolVar);
    In this line, we print out the Boolean value stored in boolVar.

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.

dart