Dears
I want to have abstract generic class with the following pattern My phone model is as follows:
class Phone extends ModelInterface {
...
@override
static dynamic getErrorInstance(Map<String, dynamic> map) {
return Phone.fromErrors(map);
}
@override
static dynamic getResponseInstance(Map<String, dynamic> map) {
return Phone.fromMap(map);
}
}
As you can see the Phone model extends ModelInterface and there are two overriden methods getErrorInstance and getResponseInstance
These two methods are defined as static in the ModelInterface abstract class
abstract class ModelInterface {
static dynamic getErrorInstance(Map<String, dynamic> map) {}
static dynamic getResponseInstance(Map<String, dynamic> map) {}
}
What I wanted to do is to create a generic method that builds the object based on response type shown below
abstract class Base {
...
T getModel<T extends ModelInterface>(Map<String, dynamic> map) {
if (hasErrors(map)) {
return T.getErrorInstance(map);
}
return T.getResponseInstance(map);
}
}
And the client for this method getModel shown below
class UserAuth extends Base {
Future<Phone> registerPhone(Phone phone) async {
String url = Routes.phoneUrl;
String body = json.encode(phone.toMap());
final response = await http.post(url, body: body, headers: Routes.headers);
final responseBody = json.decode(response.body);
// here I want the generic type to be phone
return getModel<Phone>(responseBody);
}
}
However I am getting this error

Thanks
Actually I fixed it by passing in another generic Parameter such as below
T getModel<T extends ModelInterface>(Map<String, dynamic> map, T) {
if (hasErrors(map)) {
return T.getErrorInstance(map);
}
return T.getResponseInstance(map);
}
And for the client code I added the below
class UserAuth extends Base {
Future<Phone> registerPhone(Phone phone) async {
String url = Routes.phoneUrl;
String body = json.encode(phone.toMap());
final response = await http.post(url, body: body, headers: Routes.headers);
final responseBody = json.decode(response.body);
return getModel<Phone>(responseBody, Phone.empty());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With