Files
xianyan/lib/core/network/api_response.dart
Developer 794da27193 refactor: 完成存储层迁移,替换AppKVStore为KvStorage
主要变更:
1. 重构存储层导入路径,将app_kv_store替换为kv_storage
2. 移除AppKVStore初始化代码,统一使用KvStorage
3. 修复壁纸健康检测逻辑,使用最新检查时间判断检测间隔
4. 调整主页头部容器高度与裁剪行为
5. 新增引导页下次显示开关与Riverpod提供者
6. 修复API响应List类型转换崩溃问题
7. 优化部分文件头注释格式
2026-05-24 05:54:14 +08:00

63 lines
1.7 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ============================================================
// 闲言APP — API 统一响应模型
// 创建时间: 2026-04-28
// 更新时间: 2026-05-24
// 作用: 统一后端API响应格式解析
// 上次更新: 修复data字段为List时类型转换崩溃增加List→Map安全提取逻辑
// ============================================================
class ApiResponse<T> {
const ApiResponse({
required this.code,
required this.msg,
this.data,
this.time,
});
final int code;
final String msg;
final T? data;
final String? time;
bool get isSuccess => code == 1;
bool get isFail => code == 0;
bool get isUnauthorized => code == -1 || code == 401;
factory ApiResponse.fromJson(
Map<String, dynamic> json, [
T Function(dynamic)? fromData,
]) {
final rawData = json['data'];
T? parsedData;
if (rawData != null && fromData != null) {
parsedData = fromData(rawData);
} else if (rawData is T) {
parsedData = rawData;
} else if (rawData is List) {
parsedData = _tryExtractFromList(rawData);
} else {
parsedData = null;
}
return ApiResponse<T>(
code: json['code'] as int? ?? 0,
msg: json['msg'] as String? ?? '',
data: parsedData,
time: json['time']?.toString(),
);
}
/// API返回List而非期望的Map时尝试提取首个Map元素
static T? _tryExtractFromList<T>(List<dynamic> list) {
if (list.isEmpty) return null;
final first = list.first;
if (first is T) return first;
if (first is Map && T == Map<String, dynamic>) {
return Map<String, dynamic>.from(first) as T;
}
return null;
}
@override
String toString() => 'ApiResponse(code: $code, msg: $msg, data: $data)';
}