I have a model which extends a master model and need to pass the ExtendedModel to the parse method which accepts a generic class type so that I can pass any model which extends MasterModel and can call T.fromJson();
but I get an error as factory method can not be used as override.
class MasterModel {
MasterModel();
factory MasterModel.fromJson(Map<String, dynamic> json){
return MasterModel();
}
}
class ExtendedModel extends MasterModel {
int id;
String name;
ExtendedModel(this.id, this.name);
factory ExtendedModel.fromJson(Map<String, dynamic> json) {
return ExtendedModel(json['id'], json['name']);
}
}
T parse<T extends MasterModel>(Map<String, dynamic> json) {
return T.fromJson(json) as T; // Error : The method 'fromJson' isn't defined for the type 'Type'
}
I have also tried to use the normal method like
abstract class MasterModel {
MasterModel fromJson(Map<String, dynamic> json);
}
But here while calling the fromJson in parse method we need a object of class but we are creating a object in parse method so can not use this as well.
Another way is to have if conditions in the parse method like
T parse<T extends MasterModel>(Map<String, dynamic> json) {
if(T is ExtendedModel){
return ExtendedModel.fromJson(
json) as T;
}else {
// handle for other models
}
}
but this method has to be a generic method and I don't want to include the if condition to check types every time.
I am using this way, maybe it will be useful for you.
Base model;
My user model;
This is the method I'm requesting;
Since I know the return type when sending a request to the API, I specify it so that it knows what to parse ( T )