Dart Flutter 通用 API 响应类 动态类型数据类

5

我的应用目前使用自定义类作为每个API响应的模型。

但我正在尝试更改它,以优化一些小细节,所以我正在尝试实现一个名为ApiResponse的类包装器。

但静态调用和方法不起作用,无法进行fromJson和toJson转换。

我会举个例子来说明我正在尝试的内容。

MyModel -> 响应的类。 ApiResponse -> 包含任何模型类的主类,并必须作为其本身调用子方法'fromjson/tojson'。 Test -> 用于测试目的的类,错误注释在类中。

class MyModel {
  String id;
  String title;
  MyModel({this.id, this.title});

  factory MyModel.fromJson(Map<String, dynamic> json) {
    return MyModel(
      id: json["id"],
      title: json["title"],
    );
  }

  Map<String, dynamic> toJson() => {
        "id": this.id,
        "title": this.title,
      };
}

class ApiResponse<T> {
  bool status;
  String message;
  T data;
  ApiResponse({this.status, this.message, this.data});

  factory ApiResponse.fromJson(Map<String, dynamic> json) {
    return ApiResponse<T>(
        status: json["status"],
        message: json["message"],
        data: (T).fromJson(json["data"])); // The method 'fromJson' isn't defined for the type 'Type'.
                                           // Try correcting the name to the name of an existing method, or defining a method named 'fromJson'.
  }

  Map<String, dynamic> toJson() => {
        "status": this.status,
        "message": this.message,
        "data": this.data.toJson(), // The method 'toJson' isn't defined for the type 'Object'.
                                    // Try correcting the name to the name of an existing method, or defining a method named 'toJson'
      };
}

class Test {
  test() {
    ApiResponse apiResponse = ApiResponse<MyModel>();
    var json = apiResponse.toJson();
    var response = ApiResponse<MyModel>.fromJson(json);
  }
}
4个回答

11
由于静态方法必须在编译时解析,而类型在运行时之前没有值,因此您无法在Dart上调用类型的方法。
但是,您可以将解析器回调传递给构造函数并使用接口(例如Serializable),每个模型都可以实现该接口。然后,通过将您的ApiResponse更新为ApiResponse<T extends Serializable>,它将知道每个类型T都将有一个toJson()方法。
以下是完整的示例更新。
class MyModel implements Serializable {
  String id;
  String title;
  MyModel({this.id, this.title});

  factory MyModel.fromJson(Map<String, dynamic> json) {
    return MyModel(
      id: json["id"],
      title: json["title"],
    );
  }

  @override
  Map<String, dynamic> toJson() => {
        "id": this.id,
        "title": this.title,
      };
}

class ApiResponse<T extends Serializable> {
  bool status;
  String message;
  T data;
  ApiResponse({this.status, this.message, this.data});

  factory ApiResponse.fromJson(Map<String, dynamic> json, Function(Map<String, dynamic>) create) {
      return ApiResponse<T>(
      status: json["status"],
      message: json["message"],
      data: create(json["data"]),
    );
  }

  Map<String, dynamic> toJson() => {
        "status": this.status,
        "message": this.message,
        "data": this.data.toJson(),
      };
}

abstract class Serializable {
  Map<String, dynamic> toJson();
}

class Test {
  test() {
    ApiResponse apiResponse = ApiResponse<MyModel>();
    var json = apiResponse.toJson();
    var response = ApiResponse<MyModel>.fromJson(json, (data) => MyModel.fromJson(data));
  }
}

看起来工作正常,但现在的问题是,当我在控制器中获取响应时,例如,我无法获取模型的数据:response.data.title 'The getter'id' isn't defined for the type 'Serializable'. 尝试导入定义'id'的库,将名称更正为现有getter的名称,或定义名为'id'的getter或字段。 这是一个问题,因为我需要模型的数据,我将拥有许多模型和属性。 在这种情况下,您会怎么做? - Alberto Acuña
你是说你不能执行 response.data.id 吗?这应该没有问题。 - Miguel Ruivo
我的意思是在测试响应下是的,但我正在进行一个Flutter TDD项目,所以所有这些过程都在远程数据源内部进行,因此它返回ApiResponse类,现在在下一级中,我只需获取响应ApiResponse response,例如,所以现在没有办法我无法获取response.data.id。你明白我想说什么吗? - Alberto Acuña
谢谢您的回复,对我帮助很大。但是如果有一个 List<MyModel> 呢? - Frade
应该以同样的方式运行,因为它是 MyModel 的集合,而 MyModel 本身是可序列化的。 - Miguel Ruivo
显示剩余2条评论

9

base_response.dart

class BaseResponse {
  dynamic message;
  bool success;


  BaseResponse(
      {this.message, this.success});

  factory BaseResponse.fromJson(Map<String, dynamic> json) {
    return BaseResponse(
        success: json["success"],
        message: json["message"]);
  }
}

list_response.dart

server response for list
{
  "data": []
  "message": null,
  "success": true,
}

@JsonSerializable(genericArgumentFactories: true)
class ListResponse<T> extends BaseResponse {
  List<T> data;

  ListResponse({
    String message,
    bool success,
    this.data,
  }) : super(message: message, success: success);

  factory ListResponse.fromJson(Map<String, dynamic> json, Function(Map<String, dynamic>) create) {
    var data = List<T>();
    json['data'].forEach((v) {
      data.add(create(v));
    });

    return ListResponse<T>(
        success: json["success"],
        message: json["message"],
        data: data);
  }
}

single_response.dart

server response for single object
{
  "data": {}
  "message": null,
  "success": true,
}


@JsonSerializable(genericArgumentFactories: true)
class SingleResponse<T> extends BaseResponse {
  T data;

  SingleResponse({
    String message,
    bool success,
    this.data,
  }) : super(message: message, success: success);

  factory SingleResponse.fromJson(Map<String, dynamic> json, Function(Map<String, dynamic>) create) {
    return SingleResponse<T>(
        success: json["success"],
        message: json["message"],
        data: create(json["data"]));
  }
}

data_response.dart

class DataResponse<T> {
  Status status;
  T res; //dynamic
  String loadingMessage;
  GeneralError error;

  DataResponse.init() : status = Status.Init;

  DataResponse.loading({this.loadingMessage}) : status = Status.Loading;

  DataResponse.success(this.res) : status = Status.Success;

  DataResponse.error(this.error) : status = Status.Error;


  @override
  String toString() {
    return "Status : $status \n Message : $loadingMessage \n Data : $res";
  }
}

enum Status {
  Init,
  Loading,
  Success,
  Error,
}

或者如果使用freeezed,那么data_response可以是

@freezed
abstract class DataResponse<T> with _$DataResponse<T> {
  const factory DataResponse.init() = Init;
  const factory DataResponse.loading(loadingMessage) = Loading;
  const factory DataResponse.success(T res) = Success<T>;
  const factory DataResponse.error(GeneralError error) = Error;
}

用法:(Retrofit库的一部分)

@GET(yourEndPoint)
Future<SingleResponse<User>> getUser();

@GET(yourEndPoint)
Future<ListResponse<User>> getUserList();

如果不使用Retrofit:
const _extra = <String, dynamic>{};
final queryParameters = <String, dynamic>{};
final _data = <String, dynamic>{};
final _result = await _dio.request<Map<String, dynamic>>('$commentID',
    queryParameters: queryParameters,
    options: RequestOptions(
        method: 'GET',
        headers: <String, dynamic>{},
        extra: _extra,
        baseUrl: baseUrl),
    data: _data);
final value = SingleResponse<Comment>.fromJson(
  _result.data,
  (json) => Comment.fromJson(json),
);

这对我来说是更好的方法。它允许在Flutter Retrofit中使用代码生成器。@JsonSerializable(genericArgumentFactories: true) - 这非常有用。 - FarhanShares
感谢@JsonSerializable(genericArgumentFactories: true)的帮助。 Retrofit支持动态泛型fromJson代码生成。 - Gowtham K K

1
你可以尝试我的方法来应用通用响应:APIResponse<MyModel>,通过实现自定义的可解码抽象类,从http请求中返回的响应将作为MyModel对象返回。
Future<User> fetchUser() async {

    final client = APIClient();

    final result = await client.request<APIResponse<User>>(
      manager: APIRoute(APIType.getUser), 
      create: () => APIResponse<User>(create: () => User())
    );

    final user = result.response.data; // reponse.data will map with User

    if (user != null) {
      return user;
    }

    throw ErrorResponse(message: 'User not found');

}

这是我的源代码: https://github.com/katafo/flutter-generic-api-response


0
There is another way, 

Map<String, dynamic> toJson() => {
        "message": message,
        "status": status,
        "data": _toJson<T>(data),
      };

static T _fromJson<T>(Map<String, dynamic> json) {
    return ResponseModel.fromJson(json) as T;
  }

序列化会给你带来问题。 - Alberto Acuña

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接