站点登录
This commit is contained in:
@@ -1,19 +1,75 @@
|
||||
class BaseModel {
|
||||
bool? success;
|
||||
String? type;
|
||||
String? url;
|
||||
/// 通用的 API 响应基础模型
|
||||
/// 使用泛型 <T> 来适应 'data' 字段中任何可能的数据类型
|
||||
class BaseModel<T> {
|
||||
final int code; // 状态码,0正常,其他异常
|
||||
final bool status; // 状态布尔值,true正常,false异常
|
||||
final String message; // 消息,例如 "success"
|
||||
final T? data; // 核心数据,使用泛型 T,可以是任何类型
|
||||
final int time; // 时间戳
|
||||
final dynamic error; // 错误信息,可以是任何类型或 null
|
||||
|
||||
BaseModel({this.success, this.type, this.url});
|
||||
BaseModel({
|
||||
required this.code,
|
||||
required this.status,
|
||||
required this.message,
|
||||
this.data, // data 可以为 null
|
||||
required this.time,
|
||||
this.error, // error 可以为 null
|
||||
});
|
||||
|
||||
factory BaseModel.fromJson(Map<String, dynamic> json) => BaseModel(
|
||||
success: json['success']?.toString().contains("true"),
|
||||
type: json['type']?.toString(),
|
||||
url: json['url']?.toString(),
|
||||
);
|
||||
/// fromJson 工厂构造函数(重构后)
|
||||
factory BaseModel.fromJson(
|
||||
Map<String, dynamic> json, {
|
||||
T? Function(dynamic dataJson)? dataBuilder,
|
||||
}) {
|
||||
// 使用一个辅助函数来安全地转换类型,防止因类型不匹配(如 "0" vs 0)而崩溃
|
||||
int _parseInt(dynamic value) {
|
||||
if (value is int) return value;
|
||||
if (value is String) return int.tryParse(value) ?? -1;
|
||||
return -1;
|
||||
}
|
||||
|
||||
T? finalData;
|
||||
|
||||
// 检查 'data' 字段是否存在
|
||||
if (json.containsKey('data') && json['data'] != null) {
|
||||
if (dataBuilder != null) {
|
||||
// 如果提供了 dataBuilder,就用它来解析成具体的 T 类型对象
|
||||
finalData = dataBuilder(json['data']);
|
||||
} else {
|
||||
// 如果没有提供 dataBuilder,但 T 不是 dynamic,我们假设 data 就是 T 类型
|
||||
// 这在使用 BaseModel<Map<String, dynamic>> 时很有用
|
||||
if (T != dynamic) {
|
||||
try {
|
||||
finalData = json['data'] as T?;
|
||||
} catch(e) {
|
||||
// 如果直接转换失败,保持为 null,避免崩溃
|
||||
finalData = null;
|
||||
}
|
||||
} else {
|
||||
// 如果 T 是 dynamic,直接赋值
|
||||
finalData = json['data'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return BaseModel<T>(
|
||||
code: _parseInt(json['code']),
|
||||
status: json['status'] as bool? ?? false,
|
||||
message: json['message']?.toString() ?? 'No message',
|
||||
time: _parseInt(json['time']),
|
||||
data: finalData,
|
||||
error: json['error'],
|
||||
);
|
||||
}
|
||||
|
||||
/// toJson 方法 (可选)
|
||||
Map<String, dynamic> toJson() => {
|
||||
if (success != null) 'success': success,
|
||||
if (type != null) 'type': type,
|
||||
if (url != null) 'url': url,
|
||||
};
|
||||
'code': code,
|
||||
'status': status,
|
||||
'message': message,
|
||||
'time': time,
|
||||
'data': data,
|
||||
'error': error,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user