如何在flutter / dart中创建通用类型的对象?

问题描述 投票:2回答:1

我们如何在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;
}

任何人都可以帮助我解决该错误吗?

json flutter dart
1个回答
0
投票

您需要将T强制转换为BaseResponse

data = (T as BaseResponse).fromJson(json['data']);
© www.soinside.com 2019 - 2024. All rights reserved.