简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM