Home > Software engineering >  Flutter converting String to Boolean
Flutter converting String to Boolean

Time:04-13

I am having a String that i would like to convert to Boolean Below is how the string looks like


String isValid = "false";

The String isValid can either be true or false

Is there a way i can directly convert this String isValid to Boolean. I have tried Sample questions and solutions but they are just converting Strings which are hard coded, for example most of the answers are just when the string is true

CodePudding user response:

This example can work for you, either if is false or true:

  String isValid = "true";
  
  bool newBoolValue = isValid.toLowerCase() != "false";
  
  print(newBoolValue);

CodePudding user response:

You can use extensions like this

bool toBoolean() {
   String str = this!;
   return str != '0' && str != 'false' && str != '';
}

CodePudding user response:

On top of my head, you can create an extension method for string data-type for your own need with all sorts of requirements checks and custom exceptions to beautify your desired functionalities. Here is an example:

import 'package:test/expect.dart';

void main(List<String> args) {
  String isValid = "true";

  print(isValid.toBoolean());
}

extension on String {
  bool toBoolean() {
    print(this);
    return (this.toLowerCase() == "true" || this.toLowerCase() == "1")
        ? true
        : (this.toLowerCase() == "false" || this.toLowerCase() == "0"
            ? false
            : throwsUnsupportedError);
  }
}

Here, in this example, I've created a variable named isValid in the main() method, which contains a string value. But, look closely at how I've parsed the string value to a bool value using the power with extension declared just a few lines below.

Same way, you can access the newly created string-extension method toBoolean() from anywhere. Keep in mind, if you're not in the same file where the toBoolean() extension is created, don't forget to import the proper reference.

Bonus tips: You can also access toBoolean() like this,

bool alternateValidation = "true".toBoolean();

Happy coding

  • Related