[英]Flutter Class inherence
I'm having problems with super and sub classses contructors.我在使用超级类和子类构造函数时遇到问题。 I have a set of variables declared in the super class, and I call super on my subclasses, but then I cannot acess the superclass variables through the sub-classes.
我在 super class 中声明了一组变量,我在我的子类上调用了 super,但是我无法通过子类访问超类变量。
As shown below, in my fromJson method, I cannot acess the userRating field in TennisAttributes.如下所示,在我的 fromJson 方法中,我无法访问 TennisAttributes 中的 userRating 字段。
abstract class UserSportAttributes {
int selfRating;
int userRating;
String description;
int gamesPlayed;
UserSportAttributes({
required this.selfRating,
required this.description,
this.gamesPlayed = 0,
this.userRating = 0,
});
Map<String, dynamic> toJson() => {
'SelfRating': selfRating,
'UserRating': userRating,
'Description': description,
};
static fromJson(Map<String, dynamic> json, String sportName) {
if (sportName == "Tennis") {
return TennisAttributes(
selfRating: json['SelfRating'],
userRating: json['UserRating'], //error
description: json['Description']);
}
---------
class TennisAttributes extends UserSportAttributes {
TennisAttributes({required int selfRating, required String description})
: super(selfRating: selfRating, description: description);
}
You need to have TennisAttributes
constructor property, like您需要具有
TennisAttributes
构造函数属性,例如
class TennisAttributes extends UserSportAttributes {
TennisAttributes({
required int selfRating,
required String description,
required int userRating, //this one
})...
You can also do你也可以这样做
class TennisAttributes extends UserSportAttributes {
TennisAttributes({
required super.selfRating,
required super.description,
required super.userRating,
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.