/// ============================================================ /// 【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 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 toJson() { return {'id': id, 'userId': userId, 'title': title, 'body': body}; } }