docs(course): enrich lesson scripts with code checkpoints and troubleshooting
This commit is contained in:
1 parent
0469a45f51
commit
5406a7de02
3 files changed
+459
-234
No files matched your search
+310
-134
@@ -1,158 +1,334 @@
|
||||
# 第6节|KMP 商城(实操课件)
|
||||
## 主题:共享层网络 + 持久化购物车(先跑通基础流程)
|
||||
# 第6节|KMP 商城实操讲稿(可跟敲)
|
||||
## 主题:shared 共享层网络 + 本地持久化(把数据链路真正跑通)
|
||||
|
||||
> 目标:本节跟着敲完后,能实现 **商品列表加载 + 加入购物车 + 重启不丢购物车**。
|
||||
> 这份讲稿是“边讲边敲”的版本。按步骤走,课堂上能稳定跑出:
|
||||
> 1)商品列表加载;2)加入购物车;3)重启后购物车不丢。
|
||||
|
||||
---
|
||||
|
||||
## 0. 本节最终效果(验收口径)
|
||||
## 一、课前准备(讲师先做)
|
||||
|
||||
- 首页能从后端拿到商品列表
|
||||
- 点击“加购”后,购物车数量变化
|
||||
- 退出重进后,购物车数量仍然在
|
||||
- 先不追求 UI 花哨,先把链路打通
|
||||
### 1. 环境
|
||||
- JDK 17
|
||||
- Android Studio 最新稳定版
|
||||
- 可运行 Android 模拟器或真机
|
||||
|
||||
---
|
||||
### 2. 项目结构检查
|
||||
确认项目是 KMP Wizard 标准结构:
|
||||
|
||||
## 1. 项目准备(5分钟)
|
||||
```text
|
||||
kmp-mini-shopping/
|
||||
├─ composeApp/ # Android UI 层
|
||||
├─ shared/ # 共享业务层
|
||||
│ ├─ src/commonMain
|
||||
│ ├─ src/androidMain
|
||||
│ └─ src/iosMain
|
||||
└─ docs/
|
||||
```
|
||||
|
||||
1. 使用 KMP Wizard 创建项目(Android + iOS SwiftUI)
|
||||
2. 约定目录职责:
|
||||
- `composeApp`:Android UI
|
||||
- `shared/commonMain`:共享业务(网络、存储、仓储)
|
||||
3. AndroidManifest 保留网络权限:
|
||||
### 3. AndroidManifest 网络权限
|
||||
`composeApp/src/androidMain/AndroidManifest.xml`
|
||||
|
||||
```xml
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. shared 层依赖配置(10分钟)
|
||||
|
||||
在 `shared/build.gradle.kts`(或版本目录统一管理)确保有:
|
||||
|
||||
- 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+ 放开明文(开发环境):
|
||||
如果课堂接 HTTP(局域网后端),`application` 里加:
|
||||
|
||||
```xml
|
||||
<application
|
||||
android:usesCleartextTraffic="true"
|
||||
... />
|
||||
android:usesCleartextTraffic="true"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. 本节验收清单(5分钟)
|
||||
## 二、本节目标(开场 2 分钟)
|
||||
|
||||
- [ ] 列表加载成功
|
||||
- [ ] 可加购
|
||||
- [ ] 总件数实时变化
|
||||
- [ ] 重启后购物车仍存在
|
||||
今天只做三件事:
|
||||
|
||||
1. 在 `shared` 实现商品网络请求(Ktor)
|
||||
2. 在 `shared` 实现购物车持久化(Settings)
|
||||
3. Android 页面只做“展示 + 调用 shared”
|
||||
|
||||
> 强调:业务规则都在 shared,不写死在 Android 页面里。
|
||||
|
||||
---
|
||||
|
||||
## 10. 课后作业
|
||||
## 三、依赖配置(第1段:10分钟)
|
||||
|
||||
1. 给列表加搜索框(标题/描述过滤)
|
||||
2. 给购物车加“清空”按钮
|
||||
3. 截图提交:列表页 + 购物车计数变化
|
||||
> 目标:让 shared 能发请求、能序列化、能存本地。
|
||||
|
||||
### 1. `shared/build.gradle.kts`
|
||||
确认(或添加)这些依赖:
|
||||
|
||||
- `ktor-client-core`
|
||||
- `ktor-client-content-negotiation`
|
||||
- `ktor-serialization-kotlinx-json`
|
||||
- `multiplatform-settings-no-arg`
|
||||
- `kotlinx-serialization`
|
||||
|
||||
Android 侧引擎(`shared/androidMain`)需要:
|
||||
- `ktor-client-okhttp`(或 Android 引擎)
|
||||
|
||||
> 你项目里如果用了 `libs.versions.toml`,按版本目录方式加;课堂不纠结版本细节。
|
||||
|
||||
---
|
||||
|
||||
## 四、共享模型(第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<Product> {
|
||||
if (useMock) return mockProducts()
|
||||
return client.get("$baseUrl/products").body()
|
||||
}
|
||||
|
||||
private fun mockProducts(): List<Product> = 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<CartItem> {
|
||||
val raw = settings.getStringOrNull(key) ?: return emptyList()
|
||||
return runCatching { json.decodeFromString<List<CartItem>>(raw) }
|
||||
.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
fun save(items: List<CartItem>) {
|
||||
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<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()
|
||||
}
|
||||
|
||||
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<Product> = emptyList()
|
||||
) {
|
||||
suspend fun getProducts(): List<Product> = 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 install`(Ktor)
|
||||
补 import:
|
||||
```kotlin
|
||||
import io.ktor.server.application.install
|
||||
```
|
||||
|
||||
### 2)Android 真机请求 HTTP 不通
|
||||
- Manifest 是否有 `usesCleartextTraffic=true`
|
||||
- 后端地址必须是局域网 IP,不是 `localhost`
|
||||
|
||||
### 3)商品返回有数据,但 UI 显示“没有匹配”
|
||||
- 搜索词有空格残留(`trim()`)
|
||||
- 过滤逻辑误伤
|
||||
|
||||
---
|
||||
|
||||
## 十、本节验收(最后5分钟)
|
||||
|
||||
- [ ] shared 有 ProductApi / ProductRepository / CartRepository
|
||||
- [ ] Android 列表能显示
|
||||
- [ ] 加购后总件数变化
|
||||
- [ ] 退出重开购物车仍在
|
||||
|
||||
---
|
||||
|
||||
## 十一、作业(课后)
|
||||
|
||||
1. 列表加搜索
|
||||
2. 购物车加清空
|
||||
3. 提交:两张截图(列表+购物车)
|
||||
Reference in new issue
Block a user