示例工程 ch13-network
ch13-network/lib/src/post.dart
/// 领域模型:只关心业务字段,解析逻辑独立于 HTTP。
library;
class Post {
const Post({required this.id, required this.userId, required this.title, required this.body});
/// 手写解析(ch12 的模式):字段缺失/类型错时抛 TypeError,由网络层包装成 ParseException。
factory Post.fromJson(Map<String, Object?> json) => Post(
id: (json['id'] as num).toInt(),
userId: (json['userId'] as num?)?.toInt() ?? 0,
title: json['title'] as String? ?? '',
body: json['body'] as String? ?? '',
);
final int id;
final int userId;
final String title;
final String body;
@override
bool operator ==(Object other) => other is Post && other.id == id;
@override
int get hashCode => id.hashCode;
@override
String toString() => 'Post($id, $title)';
}