Search code examples
flutterdartinheritancesuperclass

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.

As shown below, in my fromJson method, I cannot acess the userRating field in TennisAttributes.

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);
}

Solution

  • You need to have TennisAttributes constructor property, like

    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,
      });
    }