How can we create object of generic types in dart?
For my use case, each of my api responses are wrapped as ApiResponse class. For login api response, I get a json object such as
{
"data": {
"email": "[email protected]",
"name": "A"
},
"message": "Successful",
"status": true
}
So to parse these responses, I created classes as below, but they throw compile time error stating that The method 'fromJson' isn't defined for the class 'Type'. :
class ApiResponse<T extends BaseResponse> {
bool status;
String message;
T data;
ApiResponse.fromJson(Map<String, dynamic> json) {
status = json['status'];
message = json['message'];
data = T.fromJson(json['data']); // <<<------- here is the compile time error
}
}
abstract class BaseResponse {
BaseResponse.fromJson(Map<String, dynamic> json);
}
class Login extends BaseResponse {
String name, email;
Login.fromJson(Map<String, dynamic> json) : super.fromJson(json) {
name = json['name'];
email = json['email'];
}
}
// and I want to use it like below
usage() {
ApiResponse<Login> a = ApiResponse.fromJson({});
String name = a.data.name;
}
Can anyone help me fix the error?
data = data.fromJson(json['data'])data = data.fromJson(json['data']):: main.dart:9:17: Error: The method 'fromJson' isn't defined for the class 'BaseResponse'. - 'BaseResponse' is from 'main.dart'. data = data.fromJson(json['data']); ^^^^^^^^ Error: Compilation failed.