2025-09-01 10:24:46 +08:00
|
|
|
class ApiResponse<T> {
|
2025-09-01 18:20:05 +08:00
|
|
|
final String? description;
|
2025-09-01 10:24:46 +08:00
|
|
|
final T? data;
|
2025-09-01 18:20:05 +08:00
|
|
|
final String? errorMsg;
|
|
|
|
|
final int? errorCode;
|
2025-09-01 10:24:46 +08:00
|
|
|
|
|
|
|
|
const ApiResponse({
|
2025-09-01 18:20:05 +08:00
|
|
|
this.description,
|
2025-09-01 10:24:46 +08:00
|
|
|
this.data,
|
2025-09-01 18:20:05 +08:00
|
|
|
this.errorMsg,
|
|
|
|
|
this.errorCode,
|
2025-09-01 10:24:46 +08:00
|
|
|
});
|
|
|
|
|
|
2025-09-01 18:20:05 +08:00
|
|
|
// ✅ 新增:从 JSON 创建 ApiResponse
|
|
|
|
|
factory ApiResponse.fromJson(
|
|
|
|
|
Map<String, dynamic> json,
|
|
|
|
|
T Function(dynamic)? dataFromJson, // 可为空,有些接口 data 是 null
|
|
|
|
|
) {
|
|
|
|
|
final dataJson = json['data'];
|
|
|
|
|
final T? parsedData = dataJson != null && dataFromJson != null
|
|
|
|
|
? dataFromJson(dataJson)
|
|
|
|
|
: null;
|
|
|
|
|
|
2025-09-01 10:24:46 +08:00
|
|
|
return ApiResponse<T>(
|
2025-09-01 18:20:05 +08:00
|
|
|
errorCode: json['errorCode'],
|
|
|
|
|
errorMsg: json['errorMsg'],
|
|
|
|
|
description: json['description'],
|
|
|
|
|
data: parsedData,
|
2025-09-01 10:24:46 +08:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-01 18:20:05 +08:00
|
|
|
// 成功工厂构造
|
|
|
|
|
factory ApiResponse.success(T data, {
|
|
|
|
|
String? errorMsg,
|
|
|
|
|
int? errorCode,
|
|
|
|
|
String? description,
|
|
|
|
|
}) {
|
2025-09-01 10:24:46 +08:00
|
|
|
return ApiResponse<T>(
|
2025-09-01 18:20:05 +08:00
|
|
|
data: data,
|
|
|
|
|
errorMsg: errorMsg ?? 'success',
|
|
|
|
|
errorCode: errorCode,
|
|
|
|
|
description: description ?? 'success',
|
2025-09-01 10:24:46 +08:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-01 18:20:05 +08:00
|
|
|
// 失败工厂构造
|
|
|
|
|
factory ApiResponse.error(
|
|
|
|
|
String errorMsg, {
|
|
|
|
|
int? errorCode,
|
|
|
|
|
T? data,
|
|
|
|
|
String? description,
|
|
|
|
|
}) {
|
2025-09-01 10:24:46 +08:00
|
|
|
return ApiResponse<T>(
|
2025-09-01 18:20:05 +08:00
|
|
|
description: description,
|
|
|
|
|
errorMsg: errorMsg,
|
|
|
|
|
errorCode: errorCode,
|
|
|
|
|
data: data,
|
2025-09-01 10:24:46 +08:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-01 18:20:05 +08:00
|
|
|
bool get isSuccess {
|
|
|
|
|
return errorCode == 0;
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-01 10:24:46 +08:00
|
|
|
|
|
|
|
|
@override
|
|
|
|
|
String toString() {
|
2025-09-01 18:20:05 +08:00
|
|
|
return 'ApiResponse(description: $description, errorMsg: $errorMsg, data: $data, errorCode: $errorCode)';
|
2025-09-01 10:24:46 +08:00
|
|
|
}
|
2025-09-01 18:20:05 +08:00
|
|
|
}
|