Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter converting String to Boolean

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

like image 216
Emmanuel Njorodongo Avatar asked Sep 17 '25 15:09

Emmanuel Njorodongo


1 Answers

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 😊

like image 126
Omar Khaium Chowdhury Avatar answered Sep 19 '25 04:09

Omar Khaium Chowdhury