我们如何在Dart中创建泛型类型的对象?
对于我的用例,我的每个api响应都包装为ApiResponse
类。对于登录API响应,我得到一个json对象,例如
{
"data": {
"email": "[email protected]",
"name": "A"
},
"message": "Successful",
"status": true
}
因此,为了解析这些响应,我创建了以下类,但是它们引发了编译时错误,指出未为类“Type”定义方法“fromJson”。 :
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;
}
谁能帮我解决错误?
最佳答案
您需要将T
转换为BaseResponse
:
data = (T as BaseResponse).fromJson(json['data']);