You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
97 lines
2.4 KiB
97 lines
2.4 KiB
/// API响应模型基类
|
|
class BaseResponse<T> {
|
|
final int code;
|
|
final String message;
|
|
final T? data;
|
|
|
|
BaseResponse({
|
|
required this.code,
|
|
required this.message,
|
|
this.data,
|
|
});
|
|
|
|
factory BaseResponse.fromJson(Map<String, dynamic> json, T Function(dynamic)? fromJsonT) {
|
|
return BaseResponse(
|
|
code: json['code'] ?? 0,
|
|
message: json['message'] ?? '',
|
|
data: fromJsonT != null && json.containsKey('data') && json['data'] != null
|
|
? fromJsonT(json['data'])
|
|
: null,
|
|
);
|
|
}
|
|
|
|
Map<String, dynamic> toJson(Object? Function(T?)? toJsonT) {
|
|
final Map<String, dynamic> data = <String, dynamic>{};
|
|
data['code'] = code;
|
|
data['message'] = message;
|
|
if (this.data != null && toJsonT != null) {
|
|
data['data'] = toJsonT(this.data);
|
|
}
|
|
return data;
|
|
}
|
|
|
|
/// 是否请求成功
|
|
bool get isSuccess => code == 0;
|
|
|
|
@override
|
|
String toString() {
|
|
return 'BaseResponse{code: $code, message: $message, data: $data}';
|
|
}
|
|
}
|
|
|
|
/// 分页响应模型
|
|
class PaginatedResponse<T> {
|
|
final List<T> records; // 数据列表
|
|
final int total; // 总记录数
|
|
final int size; // 每页大小
|
|
final int current; // 当前页码
|
|
final int pages; // 总页数
|
|
|
|
PaginatedResponse({
|
|
required this.records,
|
|
required this.total,
|
|
required this.size,
|
|
required this.current,
|
|
required this.pages,
|
|
});
|
|
|
|
/// 是否还有更多数据
|
|
bool get hasMore => current < pages;
|
|
|
|
factory PaginatedResponse.fromJson(
|
|
Map<String, dynamic> json,
|
|
T Function(dynamic) fromJsonT,
|
|
) {
|
|
final records = <T>[];
|
|
// 支持 records 或 list 字段名
|
|
final listData = json['records'] ?? json['list'];
|
|
if (listData != null && listData is List) {
|
|
for (final item in listData) {
|
|
records.add(fromJsonT(item));
|
|
}
|
|
}
|
|
|
|
return PaginatedResponse(
|
|
records: records,
|
|
total: json['total'] ?? 0,
|
|
size: json['size'] ?? json['pageSize'] ?? 10,
|
|
current: json['current'] ?? json['page'] ?? 1,
|
|
pages: json['pages'] ?? 1,
|
|
);
|
|
}
|
|
|
|
Map<String, dynamic> toJson(Object Function(T) toJsonT) {
|
|
return {
|
|
'records': records.map((e) => toJsonT(e)).toList(),
|
|
'total': total,
|
|
'size': size,
|
|
'current': current,
|
|
'pages': pages,
|
|
};
|
|
}
|
|
|
|
@override
|
|
String toString() {
|
|
return 'PaginatedResponse{records: ${records.length} items, total: $total, current: $current, pages: $pages, size: $size}';
|
|
}
|
|
}
|