# 第6节|KMP 商城实操讲稿
## 主题:shared 共享层网络 + 本地持久化(把数据链路真正跑通)
> 按步骤完成后可稳定实现:
> 1)商品列表加载;2)加入购物车;3)重启后购物车不丢。
---
## 一、课前准备
### 1. 环境
- JDK 17
- Android Studio 最新稳定版
- 可运行 Android 模拟器或真机
### 2. 项目结构检查
确认项目是 KMP Wizard 标准结构:
```text
kmp-mini-shopping/
├─ composeApp/ # Android UI 层
├─ shared/ # 共享业务层
│ ├─ src/commonMain
│ ├─ src/androidMain
│ └─ src/iosMain
└─ docs/
```
### 3. AndroidManifest 网络权限
`composeApp/src/androidMain/AndroidManifest.xml`
```xml
```
> 课程已统一使用 HTTPS 地址:`https://shopneu.hmos.site`。
> 仅当你改回本地 HTTP 联调时,才需要 `usesCleartextTraffic=true`。
---
## 二、本节目标(开场 2 分钟)
今天只做三件事:
1. 在 `shared` 实现商品网络请求(Ktor)
2. 在 `shared` 实现购物车持久化(Settings)
3. Android 页面只做“展示 + 调用 shared”
> 强调:业务规则都在 shared,不写死在 Android 页面里。
---
## 三、依赖配置(第1段:10分钟)
> 目标:让 shared 能发请求、能序列化、能存本地。
### 1. `shared/build.gradle.kts`
直接在 `kotlin { sourceSets { ... } }` 里按下面写(可照抄):
```kotlin
kotlin {
sourceSets {
all {
languageSettings.optIn("kotlinx.cinterop.ExperimentalForeignApi")
languageSettings.optIn("kotlin.experimental.ExperimentalObjCName")
}
commonMain.dependencies {
implementation("io.ktor:ktor-client-core:3.1.3")
implementation("io.ktor:ktor-client-content-negotiation:3.1.3")
implementation("io.ktor:ktor-serialization-kotlinx-json:3.1.3")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.8.1")
implementation("com.russhwolf:multiplatform-settings-no-arg:1.1.1")
}
androidMain.dependencies {
implementation("io.ktor:ktor-client-okhttp:3.1.3")
}
iosMain.dependencies {
implementation("io.ktor:ktor-client-darwin:3.1.3")
}
}
}
```
> 如果你项目当前版本不一致,以你项目里已锁定版本为准。
### 2. Ktor 官方文档(课堂可直接贴)
- Ktor Multiplatform Client 官方教程:
`https://ktor.io/docs/client-create-multiplatform-application.html`
- Ktor Serialization 官方说明(ContentNegotiation/JSON 的用途):
`https://ktor.io/docs/server-serialization.html`
### 2.1 课程统一后端地址(已部署)
- 线上地址:`https://shopneu.hmos.site`
- 商品接口:`https://shopneu.hmos.site/api/products`(推荐)
Android 端 `baseUrl` 建议写:
```kotlin
ProductApi(baseUrl = "https://shopneu.hmos.site/api", useMock = false)
```
### 3. `content-negotiation` 是干什么的?(给学生讲)
`ktor-client-content-negotiation` + `ktor-serialization-kotlinx-json` 这两个依赖,
就是让 Ktor 能把接口返回的 JSON 自动反序列化成 Kotlin 数据类(例如 `List`)。
对应代码就是:
```kotlin
install(ContentNegotiation) {
json(Json {
ignoreUnknownKeys = true
isLenient = true
})
}
```
如果不加这两个依赖,`body>()` 这类写法会失败(无法自动解析 JSON)。
另外,`ignoreUnknownKeys = true` 的作用是:
- 当后端返回了“数据类里未定义的字段”时,不报错,直接忽略。
- 适合课堂联调和后端字段可能变动的阶段,提升稳定性。
示例:
- `Product` 只定义了 `id/title`
- 后端额外返回 `tag/extra`
- 开启 `ignoreUnknownKeys = true` 后,`id/title` 仍可正常解析。
---
## 四、共享模型(第2段:10分钟)
### Step 1:商品模型
文件:`shared/src/commonMain/kotlin/com/example/minishop/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,
val imageUrl: String = ""
)
```
### Step 2:购物车项模型
文件:`shared/src/commonMain/kotlin/com/example/minishop/cart/CartItem.kt`
```kotlin
package com.example.minishop.cart
import kotlinx.serialization.Serializable
@Serializable
data class CartItem(
val productId: String,
val quantity: Int
)
```
**课堂检查点:**
- 两个模型都加了 `@Serializable`
- `imageUrl` 给默认值,后续缺图不崩
---
## 五、网络层(第3段:20分钟)
### Step 3:HttpClient 工厂(commonMain)
文件:`shared/.../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
})
}
}
```
### Step 4:Android 实现 actual
文件:`shared/src/androidMain/.../network/HttpClientFactory.android.kt`
```kotlin
package com.example.minishop.network
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.okhttp.OkHttp
actual fun provideHttpEngine(): HttpClientEngine = OkHttp.create()
```
### Step 5:商品 API
文件:`shared/.../network/ProductApi.kt`
```kotlin
package com.example.minishop.network
import com.example.minishop.model.Product
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
class ProductApi(
private val baseUrl: String,
private val useMock: Boolean = true,
private val client: HttpClient = createHttpClient()
) {
suspend fun fetchProducts(): List {
if (useMock) return mockProducts()
return client.get("$baseUrl/products").body()
}
private fun mockProducts(): List = listOf(
Product("1", "KMP 入门课", 99.0, "跨平台开发基础课程", "https://picsum.photos/seed/kmp1/600/360"),
Product("2", "Compose 实战课", 149.0, "Compose 多端 UI 实战", "https://picsum.photos/seed/kmp2/600/360")
)
}
```
**课堂检查点:**
- `useMock=true` 时,不依赖后端也能讲
- `useMock=false` 时,准备第7节真机联调
---
## 六、购物车持久化(第4段:20分钟)
### Step 6:CartStorage
文件:`shared/.../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 = Settings(),
private val json: Json = Json { ignoreUnknownKeys = true }
) {
private val key = "cart_items"
fun load(): List {
val raw = settings.getStringOrNull(key) ?: return emptyList()
return runCatching { json.decodeFromString>(raw) }
.getOrDefault(emptyList())
}
fun save(items: List) {
settings.putString(key, json.encodeToString(items))
}
}
```
### Step 7:CartRepository
文件:`shared/.../cart/CartRepository.kt`
```kotlin
package com.example.minishop.cart
class CartRepository(
private val storage: CartStorage = CartStorage()
) {
private val map = storage.load().associateBy { it.productId }.toMutableMap()
fun items(): List = 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()
}
fun clear() {
map.clear()
persist()
}
private fun persist() = storage.save(items())
}
```
---
## 七、仓储层(第5段:10分钟)
### Step 8:ProductRepository
文件:`shared/.../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,
private val fallback: List = emptyList()
) {
suspend fun getProducts(): List = runCatching { api.fetchProducts() }.getOrDefault(fallback)
}
```
---
## 八、Android 接最小 UI(第6段:20分钟)
> 本节只接“能跑通”的最小 UI:
> - 列表显示
> - 加购按钮
> - 顶部总件数
### Step 9:在 `App.kt` 做最小调用
思路:
1. `remember` 一个 `ProductRepository`
2. `LaunchedEffect(Unit)` 拉列表
3. 点击加购调用 `cartRepository.add(product.id)`
4. 总件数用 `cartRepository.items().sumOf { it.quantity }`
---
## 九、本节常见报错与处理
### 1)`Unresolved reference: ContentNegotiation`(Ktor Client)
检查两件事:
- 依赖是否存在:`ktor-client-content-negotiation` 与 `ktor-serialization-kotlinx-json`
- import 是否正确:
```kotlin
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.serialization.kotlinx.json.json
```
### 2)接口可在浏览器打开,但 App 仍无数据
- `baseUrl` 是否为:`https://shopneu.hmos.site/api`
- 是否误开了搜索过滤(输入框残留空格/关键词)
### 3)商品返回有数据,但 UI 显示“没有匹配”
- 搜索词先 `trim()`
- 先打印“服务总数 vs 当前显示数”定位是否是过滤导致
---
## 十、本节验收(最后5分钟)
- [ ] shared 有 ProductApi / ProductRepository / CartRepository
- [ ] Android 列表能显示
- [ ] 加购后总件数变化
- [ ] 退出重开购物车仍在
---
## 十一、作业(课后)
1. 列表加搜索
2. 购物车加清空
3. 提交:两张截图(列表+购物车)