I need to abstract my model parsing system in a http request
I have an HttpClient class
class HttpClient {
Dio dio = new Dio();
Future<T> get<T extends BaseModel>(String url) {
Response response = await dio.get(url);
T.fromJson(response.body);
}
}
my BaseModel class is this:
abstract class BaseModel {
fromJson(Map<String, dynamic> json);
toJson();
}
and an example of a model:
class Person extends BaseModel {
String name;
String surname;
int age;
Person({this.name, this.surname, this.age});
Person.fromJson(Map<String, dynamic> json) {
// parse ToModel;
}
Map<String, dynamic> toJson() {
// parse toJson;
}
}
and i want to consume my HttpClient like this:
class RandomClassToConsumeHttp {
HttpClient _httpClient;
Person person;
RandomClassToConsumeHttp(this._httpClient);
void _getPerson() async {
_person = await _httpClient.get<Person>("api/getPerson");
}
}
the problem is:
I have a generic in my get method and i need the generic to extends the BaseModel class, so i always will have a implementation of fromJson(), and do the model parse based on the model type i sent to the generic
i dont know if is possible to do some generic constraints like this in dart, and i need to use fromJson from that type, anyone knows if its possible ? or if there is another solution
Future<T> get<T extends BaseModel>(String url) {
Response response = await dio.get(url);
T.fromJson(response.body);
}