Files
App.K12.Student.Miniapp_Flu…/lib/core/models/post_model.dart
T
2026-09-04 15:22:20 +08:00

45 lines
1.8 KiB
Dart
Raw 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.
/// ============================================================
/// 【PostModel】数据模型 —— JSON ↔ 强类型对象的桥梁
/// TS:接口返回就是 JS 对象,interface 只做类型提示,不用转换;
// Flutter:接口返回是通用 Map 字典,**必须通过 fromJson 把 Map 转成 Dart 类实例,才能拥有强类型、点访问、编译检查**。
///
/// 一、为什么必须有 fromJson?
/// Dio 只会把响应 JSON 解码成 Map/List,如果页面里到处写
/// data['title'],容易拼错、无类型提示、改字段要全局搜。
/// 模型类把 JSON 映射成强类型对象,编译期就能发现错误。
///
/// 二、高频坑:
/// 1. 服务端数字类型可能不稳定(int 变 double),用
/// (json['id'] as num?)?.toInt() 做防御性转换;
/// 2. 字段缺失会直接抛异常,生产环境给 ?? 兜底值;
/// 3. fromJson(响应→对象)和 toJson(对象→提交)必须成对维护。
/// ============================================================
class PostModel {
const PostModel({
required this.id,
required this.userId,
required this.title,
required this.body,
});
final int id;
final int userId;
final String title;
final String body;
/// JSON → 对象(Dio 已把 JSON 字符串解码成 Map)
factory PostModel.fromJson(Map<String, dynamic> json) {
return PostModel(
id: (json['id'] as num?)?.toInt() ?? 0,
userId: (json['userId'] as num?)?.toInt() ?? 0,
title: json['title'] as String? ?? '',
body: json['body'] as String? ?? '',
);
}
/// 对象 → JSON(用于 POST 提交给服务器)
Map<String, dynamic> toJson() {
return {'id': id, 'userId': userId, 'title': title, 'body': body};
}
}