Home > Blockchain >  how to pass generic type to superclass in dart?
how to pass generic type to superclass in dart?

Time:07-03

I have code like this

class Human<T> {  // <--- this is the superclass
  final String name;
  final T belongings;

  Human({
    required this.name,
    required this.belongings,
  });
}

class Athlete<T> extends Human { // <--- this is the subclass
  final String sportType;

  Athlete({
    required String name,
    required belongings,
    required this.sportType,
  }) : super(name: name, belongings: belongings);
}

final messi = Athlete<List<String>>( // <--- past List<String> as generic
  name: "Lionel Messi",
  belongings: ["Jersey", "Shoes"],
  sportType: "Football",
);

final belonging = messi.belongings; // <-- the data type is dynamic, not List<String>

as you can see, I want belongings property to be generic, but after I pass List<String> as a generic type when instantiating an Athlete model, I still get dynamic data type like the image below, I expect it will be List<String> .

enter image description here

CodePudding user response:

you have to declare belongings as a List within the human class like this:

final List<String> belongings;

Human({required this.belongings})

CodePudding user response:

You need to add the <T> to Human, so it's extends Human<T>.

You also need to type the required belongings, parameter, either as required T belongings,, or by using the new super-parameters feature and make it required super.belongings.

That is:

class Human<T> {
  final String name;
  final T belongings;

  Human({
    required this.name,
    required this.belongings,
  });
}

class Athlete<T> extends Human<T> { // <--- added <T>
  final String sportType;

  Athlete({
    required super.name,        // <--- used super.name
    required super.belongings,  // <--- used super.longings
    required this.sportType,    
  }); // <--- no constructor call needed when it's all "super." parameters.
}

final messi = Athlete<List<String>>(
  name: "Lionel Messi",
  belongings: ["Jersey", "Shoes"],
  sportType: "Football",
);
  •  Tags:  
  • dart
  • Related