Files
kmp-mini-shopping/docs/第7节_整合与结业实战_最终版.md
T
xiaobai e59e64ec61
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
docs: align lesson outline and homework policy
2026-03-04 15:17:47 +08:00

141 lines
3.2 KiB
Markdown
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.
# 第7节|KMP 商城:功能整合与结业实战(最终版)
> 形式:纯讲解 + 现场敲代码 + 课后作业
> 范围:整合网络/存储/业务,完成可演示商城流程
---
## 1. 本节目标
1. 完成“列表→详情→购物车→结算”全流程
2. 基于持久化购物车做总价计算
3. 结算逻辑放共享层(Android 只触发)
4. 输出结业可演示 Demo
---
## 2. 功能实现前快速校准(10分钟)
1. 检查 Ktor 引擎是否已在 `androidMain actual` 配置
2. 检查 JSON 反序列化容错(`ignoreUnknownKeys`)
3. 检查 AndroidManifest 网络权限
---
## 3. 扩展共享层:商品详情
### 3.1 `repository/ProductRepository.kt`
```kotlin
package com.example.minishop.repository
import com.example.minishop.model.Product
import com.example.minishop.network.ProductApi
class ProductRepository(
private val api: ProductApi
) {
suspend fun products(): List<Product> = api.fetchProducts()
suspend fun productDetail(id: String): Product {
// 若后端无详情接口,可先从列表中查找模拟
return products().first { it.id == id }
}
}
```
---
## 4. 扩展共享层:购物车总价与结算
### 4.1 `cart/CartService.kt`
```kotlin
package com.example.minishop.cart
import com.example.minishop.model.Product
class CartService(
private val cartRepository: CartRepository
) {
fun totalCount(): Int = cartRepository.items().sumOf { it.quantity }
fun totalPrice(productMap: Map<String, Product>): Double {
return cartRepository.items().sumOf { item ->
val p = productMap[item.productId] ?: return@sumOf 0.0
p.price * item.quantity
}
}
fun checkout(productMap: Map<String, Product>): CheckoutResult {
val amount = totalPrice(productMap)
if (amount <= 0) return CheckoutResult(false, "购物车为空")
return CheckoutResult(true, "结算成功(模拟),金额:%.2f".format(amount))
}
}
data class CheckoutResult(
val success: Boolean,
val message: String
)
```
---
## 5. Android 端整合方式(课堂实现)
页面层需要做的只有三件事:
1. 调用 `ProductRepository.products()` 渲染列表
2. 调用 `ProductRepository.productDetail(id)` 渲染详情
3. 调用 `CartRepository` / `CartService` 完成加购、总价、结算
推荐页面结构:
- 商品列表页
- 商品详情页
- 购物车页(含总价、结算按钮)
---
## 6. 课堂验收(硬标准)
1. 列表可加载
2. 详情可打开
3. 可加购、删购、改数量
4. 总价计算正确
5. 结算逻辑可执行(模拟)
6. 重启后购物车仍存在
---
## 7. 技能复盘(结业总结)
本项目中的共享层职责:
- 网络:Ktor 请求与数据解析
- 存储:Settings 持久化
- 业务:购物车规则、总价、结算
Android 职责:
- 页面展示
- 用户事件触发
- 调用共享层并渲染结果
---
## 8. 课后作业(2小时)
独立完成并提交:
1. 商品列表(Ktor 加载)
2. 商品详情(Ktor 加载)
3. 购物车(Settings 存储)
4. 加购 / 删购 / 数量修改(共享层实现)
提交物:
- 运行截图
- 关键代码截图
- 简短说明:网络/存储复用点