[英]Trim @required variables using get set in Dart
I am trying to pass a few basic strings to a User Model and then on set the strings are trimmed, but my issue is if I make the passed variables to User @required
and using the usual way of using set
and get
give me the error " Named optional parameters can't start with an underscore"
我正在尝试将一些基本字符串传递给用户 Model 然后在设置字符串被修剪,但我的问题是如果我将传递的变量传递给用户
@required
并使用通常的使用方式set
并get
给我错误" Named optional parameters can't start with an underscore"
class User {
String id;
String lastName;
String email;
String _firstName;
String get firstName => _firstName;
set firstName(String name) => _firstName = name.trim();
User({@required this.id,
@required this._firstName, // Error thrown here
@required this.lastName,
@required this.email});
}
If I do the following I get static analysis errors on the set
and get
variables saying The declaration '_firstName' isn't referenced. Try removing the declaration of '_firstName'
如果我执行以下操作,我会在
set
上得到 static 分析错误,并get
变量说The declaration '_firstName' isn't referenced. Try removing the declaration of '_firstName'
The declaration '_firstName' isn't referenced. Try removing the declaration of '_firstName'
class User {
String id;
String lastName;
String email;
String firstName;
String get _firstName => firstName; // Static analysis error here
set _firstName(String name) => _firstName = name.trim(); // Static analysis error here
User({@required this.id,
@required this.firstName,
@required this.lastName,
@required this.email});
}
Am I using get and set wrong?我使用 get 和 set 错误吗? Is there a better way to do this?
有一个更好的方法吗?
EDIT: In my opinion, in your case, there is no need to use getters and setters (see documentation :编辑:在我看来,在你的情况下,没有必要使用 getter 和 setter (参见文档:
class User {
String id;
String lastName;
String email;
String firstName;
User({
@required this.id,
@required this.firstName,
@required this.lastName,
@required this.email,
}) {
firstName = firstName.trim();
}
}
Usage:用法:
final user = User(
id: '1',
firstName: 'John',
lastName: 'Doe',
email: 'john@doe.com',
);
// set firstName :
user.firstName = 'Jane';
// get firstName :
print(user.firstName);
With getters and setters you expose a way to either get/set a value to local/private object.使用 getter 和 setter,您可以公开获取/设置值到本地/私有 object 的方法。
Something like,就像是,
String get firstname => _firstName;
set firstName => _firstName = name.trim();
From the code you've shown, if all you're trying to do, is return a trimmed value, you can do that with only getter.从您显示的代码中,如果您想要做的只是返回一个修剪后的值,那么您可以只使用 getter 来做到这一点。 Your code in that case might look as follows.
在这种情况下,您的代码可能如下所示。
class User {
String id;
String email;
final String name;
String get firstName => name.trim();
String get lastName => name.trimLeft(); //some other calculation
User({@required this.id,
@required this.name,
@required this.email});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.