docs(course): split implementation into actionable 2-lesson coding steps
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled

This commit is contained in:
xiaobai committed 2026-03-04 18:16:45 +08:00
1 parent 3c211d731a
commit 0469a45f51
3 files changed
+257 -363

No files matched your search

+131 -247
View File
@@ -1,44 +1,26 @@
# 第6节|KMP 商城:共享层网络与存储(最终版)
# 第6节|KMP 商城(实操课件)
## 主题:共享层网络 + 持久化购物车(先跑通基础流程)
> 形式:纯讲解 + 现场敲代码 + 课后作业
> 范围:仅 Android 展示,核心网络/存储全部在 shared
> 目标:本节跟着敲完后,能实现 **商品列表加载 + 加入购物车 + 重启不丢购物车**。
---
## 1. 本节目标
## 0. 本节最终效果(验收口径)
1. 在 `shared/commonMain` 完成商品列表网络加载(Ktor)
2. 在 `shared/commonMain` 完成购物车持久化(Multiplatform Settings)
3. Android 页面只调用共享层,不写业务细节
- 首页能从后端拿到商品列表
- 点击“加购”后,购物车数量变化
- 退出重进后,购物车数量仍然在
- 先不追求 UI 花哨,先把链路打通
---
## 2. 依赖配置
## 1. 项目准备(5分钟)
> 建议放入 `libs.versions.toml` 统一管理;若课堂直接写依赖,使用以下版本。
### 2.1 commonMain
```kotlin
dependencies {
implementation("io.ktor:ktor-client-core:2.3.7")
implementation("io.ktor:ktor-client-content-negotiation:2.3.7")
implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.7")
implementation("com.russhwolf:multiplatform-settings:1.1.1")
}
```
### 2.2 androidMain
```kotlin
dependencies {
implementation("io.ktor:ktor-client-android:2.3.7")
}
```
### 2.3 AndroidManifest 网络权限
`composeApp/src/androidMain/AndroidManifest.xml`
1. 使用 KMP Wizard 创建项目(Android + iOS SwiftUI)
2. 约定目录职责:
- `composeApp`:Android UI
- `shared/commonMain`:共享业务(网络、存储、仓储)
3. AndroidManifest 保留网络权限:
```xml
<uses-permission android:name="android.permission.INTERNET" />
@@ -46,229 +28,131 @@ dependencies {
---
## 3. 共享层代码结构
## 2. shared 层依赖配置(10分钟)
目标目录:
在 `shared/build.gradle.kts`(或版本目录统一管理)确保有:
```text
shared/src/commonMain/kotlin/com/example/minishop/
├─ model/
├─ network/
├─ repository/
├─ cart/
└─ platform/
- Ktor:`client-core`、`content-negotiation`、`serialization-json`
- Settings:`multiplatform-settings-no-arg`
- kotlinx.serialization
Android 端引擎:`ktor-client-okhttp`(或 Android 引擎)
---
## 3. 第一步:建共享模型(10分钟)
### 3.1 商品模型
`shared/src/commonMain/.../model/Product.kt`
字段至少包含:
- `id`
- `title`
- `price`
- `description`
- `imageUrl`(本节先可选,建议加上)
并标注 `@Serializable`。
### 3.2 购物车项模型
`shared/src/commonMain/.../cart/CartItem.kt`
字段:
- `productId`
- `quantity`
---
## 4. 第二步:建网络层(20分钟)
### 4.1 HttpClientFactory
- `HttpClientFactory.kt`(commonMain)定义 `expect/actual` 所需工厂
- Android 实现放 `androidMain/HttpClientFactory.android.kt`
### 4.2 ProductApi
`shared/.../network/ProductApi.kt`
实现:
- `suspend fun fetchProducts(): List<Product>`
- 请求路径:`GET "$baseUrl/products"`
- 本节建议保留 `useMock` 开关(课堂兜底)
---
## 5. 第三步:建购物车存储(20分钟)
### 5.1 CartStorage
`shared/.../cart/CartStorage.kt`
职责:
- `load()`:从 Settings 读取 JSON 并反序列化
- `save(items)`:持久化购物车
### 5.2 CartRepository
`shared/.../cart/CartRepository.kt`
至少包含方法:
- `items()`
- `add(productId)`
- `increase(productId)`
- `decrease(productId)`
- `remove(productId)`
- `clear()`
每次修改后调用 `persist()`。
---
## 6. 第四步:建商品仓储(10分钟)
`shared/.../repository/ProductRepository.kt`
职责:
- 对外提供 `getProducts()`
- 内部调用 `ProductApi.fetchProducts()`
- 可做异常兜底(返回 emptyList/fallback)
---
## 7. 第五步:Android 先接最小可运行 UI(20分钟)
在 `App.kt` 先实现最小页面:
1. 加载商品列表(显示标题/价格)
2. 每项有“加入购物车”按钮
3. 顶部显示总件数(来自 `CartRepository.items().sumOf { quantity }`)
> 本节不要急着做复杂架构,先“通路正确”。
---
## 8. 课堂联调(10分钟)
如果接本地后端 HTTP:
- 模拟器:`10.0.2.2`
- 真机:局域网 IP(例如 `192.168.x.x`)
- Android 9+ 放开明文(开发环境):
```xml
<application
android:usesCleartextTraffic="true"
... />
```
---
## 4. 共享模型
## 9. 本节验收清单(5分钟)
### 4.1 `model/Product.kt`
```kotlin
package com.example.minishop.model
import kotlinx.serialization.Serializable
@Serializable
data class Product(
val id: String,
val title: String,
val price: Double,
val description: String
)
```
### 4.2 `cart/CartItem.kt`
```kotlin
package com.example.minishop.cart
import kotlinx.serialization.Serializable
@Serializable
data class CartItem(
val productId: String,
val quantity: Int
)
```
- [ ] 列表加载成功
- [ ] 可加购
- [ ] 总件数实时变化
- [ ] 重启后购物车仍存在
---
## 5. Ktor 网络层
### 5.1 `network/HttpClientFactory.kt`
```kotlin
package com.example.minishop.network
import io.ktor.client.HttpClient
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json
expect fun provideHttpEngine(): HttpClientEngine
fun createHttpClient(): HttpClient = HttpClient(provideHttpEngine()) {
install(ContentNegotiation) {
json(Json {
ignoreUnknownKeys = true
isLenient = true
})
}
}
```
### 5.2 `network/HttpClientFactory.android.kt`
> 路径:`shared/src/androidMain/kotlin/com/example/minishop/network/HttpClientFactory.android.kt`
```kotlin
package com.example.minishop.network
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.android.Android
actual fun provideHttpEngine(): HttpClientEngine = Android.create()
```
### 5.3 `network/ProductApi.kt`
```kotlin
package com.example.minishop.network
import com.example.minishop.model.Product
import io.ktor.client.call.body
import io.ktor.client.request.get
class ProductApi(
private val baseUrl: String,
private val client: io.ktor.client.HttpClient = createHttpClient()
) {
suspend fun fetchProducts(): List<Product> {
return client.get("$baseUrl/products").body()
}
}
```
> 课堂可选:若无真实接口,先将 `fetchProducts()` 改为返回本地模拟列表。
---
## 6. 跨平台存储(购物车持久化)
### 6.1 `cart/CartStorage.kt`
```kotlin
package com.example.minishop.cart
import com.russhwolf.settings.Settings
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
class CartStorage(
private val settings: Settings,
private val json: Json = Json { ignoreUnknownKeys = true }
) {
private val key = "cart_items"
fun load(): List<CartItem> {
val raw = settings.getStringOrNull(key) ?: return emptyList()
return runCatching { json.decodeFromString<List<CartItem>>(raw) }.getOrElse { emptyList() }
}
fun save(items: List<CartItem>) {
settings.putString(key, json.encodeToString(items))
}
}
```
### 6.2 `cart/CartRepository.kt`
```kotlin
package com.example.minishop.cart
class CartRepository(
private val storage: CartStorage
) {
private val map = storage.load().associateBy { it.productId }.toMutableMap()
fun items(): List<CartItem> = map.values.sortedBy { it.productId }
fun add(productId: String) {
val old = map[productId]
map[productId] = if (old == null) CartItem(productId, 1) else old.copy(quantity = old.quantity + 1)
persist()
}
fun increase(productId: String) {
val old = map[productId] ?: return
map[productId] = old.copy(quantity = old.quantity + 1)
persist()
}
fun decrease(productId: String) {
val old = map[productId] ?: return
if (old.quantity <= 1) map.remove(productId) else map[productId] = old.copy(quantity = old.quantity - 1)
persist()
}
fun remove(productId: String) {
map.remove(productId)
persist()
}
private fun persist() = storage.save(items())
}
```
---
## 7. expect/actual 平台信息
### 7.1 `platform/PlatformInfo.kt`(commonMain)
```kotlin
package com.example.minishop.platform
expect fun platformName(): String
```
### 7.2 `platform/PlatformInfo.android.kt`(androidMain)
```kotlin
package com.example.minishop.platform
actual fun platformName(): String = "Android"
```
---
## 8. Android 调用共享层(最小可运行)
在 Android 页面中完成:
1. 调用 `ProductApi.fetchProducts()` 获取商品列表
2. 点击“加入购物车”调用 `CartRepository.add(productId)`
3. 刷新购物车数量(从 `CartRepository.items()` 计算)
> 页面层不保存业务规则,只保留 UI 状态与点击事件。
---
## 9. 本节验收
- 应用启动后可加载商品列表(真实或模拟)
- 点击加购后数量变化
- 重启应用后购物车数据仍存在
---
## 10. 课后作业(2小时)
1. 扩展网络接口:`fetchProductDetail(id)`
2. 补充购物车:数量修改/删除并持久化
3. Android 新增商品详情页并与购物车联动
4. 提交:运行截图(即可)
## 10. 课后作业
1. 给列表加搜索框(标题/描述过滤)
2. 给购物车加“清空”按钮
3. 截图提交:列表页 + 购物车计数变化