[英]Flutter/Dart: get and set with private variables
if I read that setters and getters have to be explicity developed in Dart only when you want to do something more than only retrieve those values.如果我读到只有当您想做的不仅仅是检索这些值时,才必须在 Dart 中明确开发 setter 和 getter。 But if I have private variables, like:
但是如果我有私有变量,比如:
Class User {
User _user;
String _password;
}
How can I access to those private variables?如何访问这些私有变量? Even if I implement the set password like
即使我实现了设置的密码
set password(String value) => _password = value;
It will of course give me an "error".它当然会给我一个“错误”。
If you want public getter/setter what's the point of having private variable for that?如果您想要公共 getter/setter,那么拥有私有变量的意义何在?
Just make it a public variable and be done.只需将其设为公共变量即可。
If you insist having a private variable with public access, then you still need to add the getter and setter.如果您坚持拥有一个具有公共访问权限的私有变量,那么您仍然需要添加 getter 和 setter。
Private variable is import due to some reasons, If you conditionally set or get your Class property values then setter and getter is important on private variables.由于某些原因,私有变量是导入的,如果您有条件地设置或获取类属性值,那么 setter 和 getter 对私有变量很重要。 Example given below:
下面给出的例子:
class User {
int _id;
String _firstName;
String _password;
int get id => _id;
set id(int value) {
_id = value;
}
String get firstName => _firstName;
set firstName(String value) {
if(value.length > 7)
_firstName = value;
}
String get password => _password;
set password(String value) {
if(some condition against this value like password)
_password = value;
}
}
Note: you can set condition in getter like setter that I have given in above example.注意:您可以像我在上面的示例中给出的 setter 一样在 getter 中设置条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.