[英]Dart private fields & vscode debugger
这是一个带有私有字段和构造函数的 class :
class User {
final String _id;
final String _username;
final String _photoUrl;
final String _bio;
final String _city;
final Map<String, dynamic> _favorite;
const User({@required String id,
@required String username,
String photoUrl,
String bio,
String city,
Map<String, dynamic> favorite
})
: this._id = id,
this._username = username,
this._photoUrl = photoUrl,
this._bio = bio,
this._city = city,
this._favorite = favorite ?? const{};
User copyWith({String id, String username, String photoUrl, String bio, String city, Map<String, dynamic> favorite}){
return User(
id: id ?? this._id,
username: username ?? this._username,
photoUrl: photoUrl ?? this._photoUrl,
bio: bio ?? this._bio,
city: city ?? this._city,
favorite: favorite ?? this._favorite,
);
}
String get id => _id;
String get username => _username;
String get photoUrl => _photoUrl;
String get bio => _bio;
String get city => _city;
Map<String, dynamic> get favorite => _favorite;
@override
int get hashCode => _id.hashCode ^ _username.hashCode ^ _photoUrl.hashCode ^ _city.hashCode ^ _bio.hashCode ^ _favorite.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is User &&
runtimeType == other.runtimeType &&
_id == other._id;
@override
String toString(){
return 'User { _id : $_id, _username : $_username, _photoUrl : $_photoUrl, _bio : $_bio, _city : $_city, _favorite : $_favorite';
}
当我使用构造函数创建 class 的实例并使用调试器观察它时,我觉得我看到了每个变量的重复:私有字段和参数。 这正常吗?
好吧,这很正常,您看到的是您的 class 的表示:所有字段和所有属性。 由于您有同名的私有字段和公共属性,因此您会“两次”看到它们,包括字段和属性。
顺便说一句,执行此操作的 Dart 方式“只是拥有公共最终字段。只需将所有字段公开,删除吸气剂即可。我猜你的 object 应该是不可变的。所以使用公共final
字段使其不可变.
例子:
class User {
final String id;
final String username;
final String photoUrl;
final String bio;
final String city;
final Map<String, dynamic> favorite;
const User({@required this.id,
@required this.username,
this.photoUrl,
this.bio,
this.city,
this.favorite
});
User copyWith({String id, String username, String photoUrl, String bio, String city, Map<String, dynamic> favorite}){
return User(
id: id ?? this.id,
username: username ?? this.username,
photoUrl: photoUrl ?? this.photoUrl,
bio: bio ?? this.bio,
city: city ?? this.city,
favorite: favorite ?? this.favorite,
);
}
@override
int get hashCode => id.hashCode ^ username.hashCode ^ photoUrl.hashCode ^ city.hashCode ^ bio.hashCode ^ favorite.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is User && runtimeType == other.runtimeType && id == other.id;
@override
String toString(){
return 'User { id : $id, username : $username, photoUrl : $photoUrl, bio : $bio, city : $city, favorite : $favorite';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.