跨平台开发 / 系统课时
改造复杂商品接口模型
改造复杂商品接口模型
复杂商品接口往往把分页、价格、库存枚举和多态促销塞在同一份响应里。直接把原始 Map 传进页面会让类型判断散落各处。本节把契约拆成 Freezed DTO,用生成代码完成反序列化,再通过 Repository 隔离数据层,并用测试锁住关键字段和多态分支。
学习目标
- 能把嵌套商品响应拆成分页、商品、价格、库存与促销 DTO。
- 能使用 Freezed union 根据
type字段解析不同促销形态。 - 能把 DTO 接入 Repository,并用自动化测试验证分页、嵌套字段和多态契约。
先冻结原始接口契约
综合改造前先保留一份代表性响应。下面的 fixture 同时包含分页信息、嵌套价格、库存状态,以及两种促销类型;后续模型和测试都围绕这份契约设计。
{
"page": 1,
"pageSize": 20,
"total": 2,
"items": [
{
"id": "p-100",
"name": "Keyboard",
"price": {"amount": 299.0, "currency": "CNY"},
"stock": {"status": "in_stock", "quantity": 8},
"promotion": {"type": "discount", "percent": 10}
},
{
"id": "p-200",
"name": "Mouse",
"price": {"amount": 129.0, "currency": "CNY"},
"stock": {"status": "out_of_stock", "quantity": 0},
"promotion": {"type": "coupon", "code": "SAVE20", "amount": 20.0}
}
]
}设计时把“传输结构”和“业务使用结构”分开:HTTP JSON 先进入 DTO,DTO 负责忠实表达接口;Repository 再把 DTO 转换成页面或领域层需要的对象。这样接口字段变化不会直接扩散到 UI。

用 Freezed 表达嵌套与多态
把以下文件放在 lib/data/product_models.dart。库存状态使用枚举约束固定值;促销使用 @Freezed(unionKey: 'type'),让生成代码根据接口里的 type 选择具体分支。
import 'package:freezed_annotation/freezed_annotation.dart';
part 'product_models.freezed.dart';
part 'product_models.g.dart';
@freezed
abstract class ProductPageDto with _$ProductPageDto {
const factory ProductPageDto({
required int page,
required int pageSize,
required int total,
required List<ProductDto> items,
}) = _ProductPageDto;
factory ProductPageDto.fromJson(Map<String, dynamic> json) =>
_$ProductPageDtoFromJson(json);
}
@freezed
abstract class ProductDto with _$ProductDto {
const factory ProductDto({
required String id,
required String name,
required PriceDto price,
required StockDto stock,
PromotionDto? promotion,
}) = _ProductDto;
factory ProductDto.fromJson(Map<String, dynamic> json) =>
_$ProductDtoFromJson(json);
}
@freezed
abstract class PriceDto with _$PriceDto {
const factory PriceDto({
required double amount,
required String currency,
}) = _PriceDto;
factory PriceDto.fromJson(Map<String, dynamic> json) =>
_$PriceDtoFromJson(json);
}
enum StockStatus {
@JsonValue('in_stock')
inStock,
@JsonValue('out_of_stock')
outOfStock,
}
@freezed
abstract class StockDto with _$StockDto {
const factory StockDto({
required StockStatus status,
required int quantity,
}) = _StockDto;
factory StockDto.fromJson(Map<String, dynamic> json) =>
_$StockDtoFromJson(json);
}
@Freezed(unionKey: 'type')
sealed class PromotionDto with _$PromotionDto {
const factory PromotionDto.discount({
required int percent,
}) = DiscountPromotionDto;
const factory PromotionDto.coupon({
required String code,
required double amount,
}) = CouponPromotionDto;
factory PromotionDto.fromJson(Map<String, dynamic> json) =>
_$PromotionDtoFromJson(json);
}生成代码:
dart run build_runner build --delete-conflicting-outputs预期结果:
Exit code: 0
Generated: lib/data/product_models.freezed.dart
Generated: lib/data/product_models.g.dart如果生成器报告冲突文件,不要手工修改 .freezed.dart 或 .g.dart;应先确认源模型和 part 文件名一致,再重新生成。
在 Repository 隔离传输模型
Repository 不应该把 DTO 原样泄漏给页面。下面是片段示例,依赖上一节的 product_models.dart 和真实的 ProductApi 实现;它把库存枚举和促销 union 转换为上层更容易消费的字段。
import 'product_models.dart';
abstract interface class ProductApi {
Future<Map<String, dynamic>> fetchProducts();
}
class ProductCard {
const ProductCard({
required this.id,
required this.name,
required this.price,
required this.inStock,
required this.promotionLabel,
});
final String id;
final String name;
final double price;
final bool inStock;
final String? promotionLabel;
}
class ProductPage {
const ProductPage({
required this.page,
required this.total,
required this.items,
});
final int page;
final int total;
final List<ProductCard> items;
}
class ProductRepository {
ProductRepository(this.api);
final ProductApi api;
Future<ProductPage> load() async {
final json = await api.fetchProducts();
final dto = ProductPageDto.fromJson(json);
return ProductPage(
page: dto.page,
total: dto.total,
items: dto.items.map((item) {
return ProductCard(
id: item.id,
name: item.name,
price: item.price.amount,
inStock: item.stock.status == StockStatus.inStock,
promotionLabel: _promotionLabel(item.promotion),
);
}).toList(growable: false),
);
}
String? _promotionLabel(PromotionDto? promotion) {
return switch (promotion) {
DiscountPromotionDto(:final percent) => '$percent% off',
CouponPromotionDto(:final code) => code,
null => null,
};
}
}这里使用 Dart 3 的模式匹配处理促销分支,避免在 Repository 中继续检查原始 type 字符串。接口如果新增第三种促销类型,模型层会先暴露变化,而不是让页面静默走到未知分支。
用测试锁住关键契约
下面的测试直接使用同一类响应结构,分别验证分页与嵌套价格、两个促销分支,以及 Repository 的最终映射。测试文件假设位于 test/product_repository_test.dart。
import 'package:flutter_test/flutter_test.dart';
import '../lib/data/product_models.dart';
import '../lib/data/product_repository.dart';
const fixture = <String, dynamic>{
'page': 1,
'pageSize': 20,
'total': 2,
'items': [
{
'id': 'p-100',
'name': 'Keyboard',
'price': {'amount': 299.0, 'currency': 'CNY'},
'stock': {'status': 'in_stock', 'quantity': 8},
'promotion': {'type': 'discount', 'percent': 10},
},
{
'id': 'p-200',
'name': 'Mouse',
'price': {'amount': 129.0, 'currency': 'CNY'},
'stock': {'status': 'out_of_stock', 'quantity': 0},
'promotion': {
'type': 'coupon',
'code': 'SAVE20',
'amount': 20.0,
},
},
],
};
class FakeProductApi implements ProductApi {
@override
Future<Map<String, dynamic>> fetchProducts() async => fixture;
}
void main() {
test('parses pagination and nested price', () {
final dto = ProductPageDto.fromJson(fixture);
expect(dto.page, 1);
expect(dto.total, 2);
expect(dto.items.first.price.amount, 299.0);
});
test('selects discount and coupon variants', () {
final dto = ProductPageDto.fromJson(fixture);
expect(dto.items[0].promotion, isA<DiscountPromotionDto>());
expect(dto.items[1].promotion, isA<CouponPromotionDto>());
});
test('repository maps the transport model', () async {
final repository = ProductRepository(FakeProductApi());
final page = await repository.load();
expect(page.items[0].inStock, isTrue);
expect(page.items[0].promotionLabel, '10% off');
expect(page.items[1].promotionLabel, 'SAVE20');
});
}运行验证:
flutter test test/product_repository_test.dart -r expanded预期输出中的时间值可能不同:
<TIME> +1: parses pagination and nested price
<TIME> +2: selects discount and coupon variants
<TIME> +3: repository maps the transport model
<TIME> +3: All tests passed!这组测试同时充当接口契约保护网。以后后端修改分页字段、库存枚举或促销 type 时,失败会集中在 DTO 解析或对应断言,而不是拖到页面渲染阶段才以空值或类型错误暴露。
控制兼容边界
综合模型改造完成后,仍要避免两个常见退化:一是为了“永远能解析”把大量字段改成 Object? 或 dynamic;二是在 Repository 里重新读取原始 Map,绕开已经建立的 DTO 约束。前者失去类型安全,后者让生成代码和测试失去价值。
合理的边界是:DTO 精确描述已知接口契约,少量历史差异由明确 converter 处理,多态结构由 union 建模;Repository 只做业务映射,不重新猜测 JSON。这样新增字段通常保持向后兼容,而字段改名、类型变化和未知促销分支会尽早失败并被测试发现。