Home > OS >  generics not able to use functions of superclass in dart/flutter
generics not able to use functions of superclass in dart/flutter

Time:06-09

I have a problem with the syntax in Dart. I want to be able to use a constructor on a generic class. So I let the generic class extend an abstract class which has the specified constructor. But the Code still shows me that it's not working. Does anyone have an idea?

T fetchItem<T extends JsonModel>(){
    return T.fromJson(); 
    // This line shows the error 
    // The method 'fromJson' isn't defined for the type 'Type'.
  }

abstract class JsonModel {
  JsonModel.fromJson();
}

The following solution works, but I think it's extremly ugly:

T fetchItem<T extends JsonModel<T>>(T t){
    return t.fromJson();
  }

abstract class JsonModel<T> {
  T fromJson();
}

CodePudding user response:

Constructors are not inherited. Just because a base class has a certain constructor, does not mean the derived class has that constructor.

It doesn't have anything to do with generics. If you extended a class X from your JsonModel, it simply would not have a constructor of that name.

  • Related