示例工程 ch09-navigation
ch09-navigation/lib/src/profile.dart
/// 资源里的领域模型:把"读文件"和"解析 JSON"分开。
///
/// 这不是过度设计——ch13 的网络层会照搬这个结构:
/// 传输(rootBundle / http)→ 原始字符串 → 纯函数解析 → 模型
/// 解析是纯函数,可以脱离 I/O 单测;传输可以被 mock。
library;
import 'dart:convert';
import 'package:flutter/foundation.dart' show immutable;
@immutable
class Profile {
const Profile({required this.name, required this.role, required this.tags});
factory Profile.fromJson(Map<String, Object?> json) => Profile(
name: json['name'] as String? ?? '未知',
role: json['role'] as String? ?? '',
tags: (json['tags'] as List<Object?>? ?? const <Object?>[])
.whereType<String>()
.toList(growable: false),
);
/// 纯函数:字符串 → 模型。不碰 I/O,测试里直接喂字符串。
factory Profile.parse(String raw) =>
Profile.fromJson(jsonDecode(raw) as Map<String, Object?>);
final String name;
final String role;
final List<String> tags;
@override
String toString() => 'Profile($name, $role, tags: $tags)';
}