Home > Back-end >  How can I create a method for the type bool in dart?
How can I create a method for the type bool in dart?

Time:08-27

I am trying to create a new method called 'reverse' to be able to change a boolean value into the opposite value, so if the value is currently true the method should return false and vice versa.

I changed the bool.dart file in my project and created the new method below the 'toString()' method

bool reverse() {
    return this ? false : true;
  }

and afterwards I used the method for my '_isLoading' boolean variable but I got this error.

Error: The method 'reverse' isn't defined for the class 'bool'. Try correcting the name to the name of an existing method, or defining a method named 'reverse'. _isLoading.reverse(); ^^^^^^^

I exited the reading mode in my bool.dart file and that also didn't work out.

CodePudding user response:

If you want to add something to bool class, try this:

extension on bool {
  bool reverse() {
    return this ? false : true;
  }
}

and call it like this:

bool x = false;
x.reverse(); // return true

CodePudding user response:

main(){
  var a = false;
  print(a); //false
  var b =a.reverse();
  print(b); //true
}

extension on bool{
  bool reverse(){
    return !this;
  }
}

More Shorter version:

extension on bool{
  bool reverse() => !this;
}

CodePudding user response:

bool reverse(bool currentValue) {
    return !currentValue; // ! will return the reverse
  }
  • Related