简体   繁体   English

如何为 dart 中的 bool 类型创建方法?

[英]How can I create a method for the type bool in dart?

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.我正在尝试创建一个名为“reverse”的新方法,以便能够将 boolean 值更改为相反的值,因此如果该值当前为 true,则该方法应返回 false,反之亦然。

I changed the bool.dart file in my project and created the new method below the 'toString()' method我在我的项目中更改了 bool.dart 文件,并在“toString()”方法下方创建了新方法

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

and afterwards I used the method for my '_isLoading' boolean variable but I got this error.之后我对我的 '_isLoading' boolean 变量使用了该方法,但我得到了这个错误。

Error: The method 'reverse' isn't defined for the class 'bool'.错误:没有为 class 'bool' 定义方法 'reverse'。 Try correcting the name to the name of an existing method, or defining a method named 'reverse'.尝试将名称更正为现有方法的名称,或定义名为“reverse”的方法。 _isLoading.reverse(); _isLoading.reverse(); ^^^^^^^ ^^^^^^^

I exited the reading mode in my bool.dart file and that also didn't work out.我在我的 bool.dart 文件中退出了阅读模式,但也没有成功。

If you want to add something to bool class, try this:如果你想添加一些东西到 bool class,试试这个:

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

and call it like this:并这样称呼它:

bool x = false;
x.reverse(); // return true
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;
}
bool reverse(bool currentValue) {
    return !currentValue; // ! will return the reverse
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM