1466 lines
40 KiB
Markdown
1466 lines
40 KiB
Markdown
# 第7节|KMP 商城实操讲稿
|
||
## 主题:SQL 升级 + 最小 MVI + 订单闭环
|
||
|
||
> 本节严格按照《第6_7节课程大纲_确认版》推进。目标不是继续堆 UI,
|
||
> 而是把第6节“能跑”的商城项目,升级为**更接近真实业务**的数据层结构。
|
||
>
|
||
> 本节最终要做出的效果:
|
||
> 1. 购物车从 Settings 升级到 SQL
|
||
> 2. 完成“购物车 → 下单 → 订单列表”闭环
|
||
> 3. 至少有 1 个核心页面按最小 MVI 管理状态
|
||
> 4. 统一错误呈现,减少异常处理分散
|
||
|
||
---
|
||
|
||
# 一、本节课前准备
|
||
|
||
## 1. 环境要求
|
||
- JDK 17
|
||
- Android Studio 最新稳定版
|
||
- Android 模拟器或真机
|
||
- 项目已经完成第6节内容:
|
||
- 商品列表网络请求
|
||
- 购物车本地持久化(Settings)
|
||
- Android 页面能展示商品并加购
|
||
|
||
## 2. 本节重要提醒
|
||
本节会引入 **SQLDelight**。
|
||
所以课堂上要强调:
|
||
|
||
- 第6节的 Settings 方案没有错
|
||
- 但它更适合保存“少量配置 / 轻量 key-value 数据”
|
||
- 如果要继续做购物车扩展、订单记录、历史数据
|
||
- 就应该升级到 **SQL**
|
||
|
||
## 3. 本节对应官方文档
|
||
### SQLDelight 官方文档
|
||
- Getting Started:
|
||
`https://sqldelight.github.io/sqldelight/2.2.1/multiplatform_sqlite/`
|
||
- Android Driver:
|
||
`https://sqldelight.github.io/sqldelight/2.2.1/android_sqlite/`
|
||
- Native Driver(iOS):
|
||
`https://sqldelight.github.io/sqldelight/2.2.1/native_sqlite/`
|
||
|
||
### 课堂说明怎么讲
|
||
不要只告诉学生“照着抄”。
|
||
要明确讲这三件事:
|
||
|
||
1. SQLDelight 是 **Kotlin Multiplatform 项目里常用的 SQL 方案**
|
||
2. 它的优势是:
|
||
- 用 `.sq` 文件写 SQL
|
||
- 自动生成类型安全的 Queries
|
||
- Android / iOS 都能共用数据库访问层
|
||
3. 这节课不是讲数据库理论,而是讲:
|
||
- 为什么这里该用 SQL
|
||
- 怎么把它安全接进现有项目
|
||
|
||
---
|
||
|
||
# 二、本节开场(建议 3~5 分钟)
|
||
|
||
第6节我们已经完成了:
|
||
- 商品列表网络请求
|
||
- 购物车本地持久化
|
||
- 基础页面交互
|
||
|
||
但现在项目还停留在“能跑”的阶段。
|
||
如果继续往真实业务推进,就会遇到两个问题:
|
||
|
||
1. **Settings 不适合复杂业务数据**
|
||
- 它适合保存登录态、主题、开关项
|
||
- 但不适合长期管理购物车、订单、历史记录
|
||
|
||
2. **状态管理会越来越乱**
|
||
- Loading / Error / Empty / Success 混在一起
|
||
- 页面越做越多,越难维护
|
||
|
||
所以第7节要做的,不是继续加几个按钮,
|
||
而是把项目底层升级到更合理的结构。
|
||
|
||
---
|
||
|
||
# 三、Step 1:为什么要从 Settings 升级到 SQL
|
||
|
||
## 本步目标
|
||
让学生理解:
|
||
**第7节引入 SQL,不是为了“更高级”,而是因为业务已经逼着我们升级。**
|
||
|
||
## 这一段课堂要讲的内容
|
||
|
||
### 1)Settings 适合什么
|
||
Settings 更适合:
|
||
- 登录态
|
||
- 开关项
|
||
- 主题配置
|
||
- 少量轻量缓存
|
||
|
||
它本质上是:
|
||
**保存一个 key 对应一个 value。**
|
||
|
||
### 2)SQL 适合什么
|
||
SQL 更适合:
|
||
- 一组结构化数据
|
||
- 增删改查
|
||
- 排序 / 筛选 / 统计
|
||
- 多对象之间的业务关系
|
||
|
||
### 3)放到当前商城项目里怎么理解
|
||
在当前项目里:
|
||
- 购物车:适合 SQL
|
||
- 订单记录:更适合 SQL
|
||
- 后续收藏 / 地址 / 浏览记录,也更适合 SQL
|
||
- 商品接口仍然可以先保持网络请求,不强行在这节课扩展缓存体系
|
||
|
||
### 4)给学生的结论
|
||
可以直接把这句话讲给学生:
|
||
|
||
> Settings 解决的是“存一个值”,
|
||
> SQL 解决的是“管理一组业务数据”。
|
||
|
||
## 本步课堂输出
|
||
到这里,学生应该明确:
|
||
- 第6节 Settings 方案没有问题
|
||
- 但第7节要继续做订单、历史记录时,必须升级到 SQL
|
||
|
||
## 本步暂时不写代码
|
||
这一部分先讲清楚动机,不着急改文件。
|
||
因为如果学生不知道为什么要改,后面代码只会机械复制。
|
||
|
||
---
|
||
|
||
# 四、Step 2:接入 SQLDelight
|
||
|
||
## 本步目标
|
||
把 SQLDelight 正确接入现有 KMP 项目,让后面可以:
|
||
- 写 `.sq` 表结构
|
||
- 生成数据库类
|
||
- 在 Android / iOS 上分别创建 driver
|
||
|
||
## 本步会改哪些内容
|
||
本步只改依赖和插件,不改业务代码:
|
||
|
||
1. `gradle/libs.versions.toml`
|
||
2. `shared/build.gradle.kts`
|
||
|
||
## 先给学生讲:SQLDelight 是怎么工作的
|
||
你可以这样解释:
|
||
|
||
1. 我们先在 Gradle 里加 SQLDelight plugin
|
||
2. 再加 Android / iOS 各自的数据库 driver
|
||
3. 再在 `shared/src/commonMain/sqldelight/` 下写 `.sq` 文件
|
||
4. SQLDelight 会自动生成:
|
||
- 数据库类
|
||
- Queries 类
|
||
- SQL 对应的数据模型
|
||
5. 我们最后在 Repository 里调用这些 Queries
|
||
|
||
这一段一定要讲,不然学生会不知道:
|
||
**“为什么我只是写了 SQL,Kotlin 里会自动多出一堆类?”**
|
||
|
||
---
|
||
|
||
## Step 2.1:修改 `gradle/libs.versions.toml`
|
||
|
||
### 文件路径
|
||
`kmp-mini-shopping/gradle/libs.versions.toml`
|
||
|
||
### 修改目标
|
||
新增:
|
||
- SQLDelight 版本号
|
||
- Android Driver
|
||
- Native Driver
|
||
- SQLDelight plugin
|
||
|
||
### 完整代码(直接替换对应部分)
|
||
|
||
```toml
|
||
[versions]
|
||
agp = "8.9.3"
|
||
androidx-activityCompose = "1.10.1"
|
||
androidx-navigationCompose = "2.9.0"
|
||
androidx-ui-tooling = "1.8.3"
|
||
androidx-viewmodelCompose = "2.9.1"
|
||
coil = "3.2.0"
|
||
compose-multiplatform = "1.8.2"
|
||
kmpObservableViewmodel = "1.0.0-BETA-12"
|
||
kmpNativeCoroutines = "1.0.0-ALPHA-45"
|
||
koin = "4.1.0"
|
||
kotlin = "2.2.0"
|
||
kotlinx-serialization = "1.8.1"
|
||
ksp = "2.2.0-2.0.2"
|
||
ktor = "3.1.3"
|
||
multiplatform-settings = "1.1.1"
|
||
sqldelight = "2.2.1"
|
||
|
||
[libraries]
|
||
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activityCompose" }
|
||
androidx-compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling", version.ref = "androidx-ui-tooling" }
|
||
androidx-compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview", version.ref = "androidx-ui-tooling" }
|
||
androidx-navigation-compose = { module = "androidx.navigation:navigation-compose", version.ref = "androidx-navigationCompose" }
|
||
androidx-viewmodel-compose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "androidx-viewmodelCompose" }
|
||
coil-compose = { group = "io.coil-kt.coil3", name = "coil-compose", version.ref = "coil" }
|
||
coil-network-ktor = { group = "io.coil-kt.coil3", name = "coil-network-ktor3", version.ref = "coil" }
|
||
kmp-observable-viewmodel = { module = "com.rickclephas.kmp:kmp-observableviewmodel-core", version.ref = "kmpObservableViewmodel" }
|
||
koin-androidx-compose = { module = "io.insert-koin:koin-androidx-compose", version.ref = "koin" }
|
||
koin-core = { module = "io.insert-koin:koin-core", version.ref = "koin" }
|
||
kotlinx-serialization-core = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core", version.ref = "kotlinx-serialization" }
|
||
ktor-client-content-negotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }
|
||
ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
|
||
ktor-client-darwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor" }
|
||
ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" }
|
||
ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }
|
||
multiplatform-settings-no-arg = { module = "com.russhwolf:multiplatform-settings-no-arg", version.ref = "multiplatform-settings" }
|
||
sqldelight-android-driver = { module = "app.cash.sqldelight:android-driver", version.ref = "sqldelight" }
|
||
sqldelight-native-driver = { module = "app.cash.sqldelight:native-driver", version.ref = "sqldelight" }
|
||
|
||
[plugins]
|
||
androidApplication = { id = "com.android.application", version.ref = "agp" }
|
||
androidLibrary = { id = "com.android.library", version.ref = "agp" }
|
||
composeCompiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
||
composeMultiplatform = { id = "org.jetbrains.compose", version.ref = "compose-multiplatform" }
|
||
kmpNativeCoroutines = { id = "com.rickclephas.kmp.nativecoroutines", version.ref = "kmpNativeCoroutines" }
|
||
kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
|
||
kotlinxSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
|
||
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
|
||
sqldelight = { id = "app.cash.sqldelight", version.ref = "sqldelight" }
|
||
```
|
||
|
||
## Step 2.1 讲解重点
|
||
### 为什么要加两个 driver?
|
||
因为 KMP 项目最终要跑在多个平台:
|
||
- Android 端需要 `android-driver`
|
||
- iOS 端需要 `native-driver`
|
||
|
||
### 为什么 plugin 要单独加?
|
||
因为 SQLDelight 不只是一个普通依赖。
|
||
它还要:
|
||
- 扫描 `.sq` 文件
|
||
- 自动生成数据库类和 Queries
|
||
|
||
所以必须加 plugin,不能只加 library。
|
||
|
||
---
|
||
|
||
## Step 2.2:修改 `shared/build.gradle.kts`
|
||
|
||
### 文件路径
|
||
`kmp-mini-shopping/shared/build.gradle.kts`
|
||
|
||
### 修改目标
|
||
1. 给 `shared` 模块加 SQLDelight plugin
|
||
2. 给 Android / iOS sourceSet 加 driver
|
||
3. 配置数据库生成类名和包名
|
||
|
||
### 完整代码(整文件直接替换)
|
||
|
||
```kotlin
|
||
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
|
||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||
|
||
plugins {
|
||
alias(libs.plugins.kotlinMultiplatform)
|
||
alias(libs.plugins.androidLibrary)
|
||
alias(libs.plugins.kotlinxSerialization)
|
||
alias(libs.plugins.ksp)
|
||
alias(libs.plugins.kmpNativeCoroutines)
|
||
alias(libs.plugins.sqldelight)
|
||
}
|
||
|
||
kotlin {
|
||
androidTarget {
|
||
@OptIn(ExperimentalKotlinGradlePluginApi::class)
|
||
compilerOptions {
|
||
jvmTarget.set(JvmTarget.JVM_11)
|
||
}
|
||
}
|
||
|
||
listOf(
|
||
iosX64(),
|
||
iosArm64(),
|
||
iosSimulatorArm64()
|
||
).forEach { iosTarget ->
|
||
iosTarget.binaries.framework {
|
||
baseName = "Shared"
|
||
isStatic = true
|
||
}
|
||
}
|
||
|
||
sourceSets {
|
||
androidMain.dependencies {
|
||
implementation(libs.ktor.client.okhttp)
|
||
implementation(libs.sqldelight.android.driver)
|
||
}
|
||
|
||
iosMain.dependencies {
|
||
implementation(libs.ktor.client.darwin)
|
||
implementation(libs.sqldelight.native.driver)
|
||
}
|
||
|
||
commonMain.dependencies {
|
||
implementation(libs.ktor.client.core)
|
||
implementation(libs.ktor.client.content.negotiation)
|
||
implementation(libs.ktor.serialization.kotlinx.json)
|
||
implementation(libs.multiplatform.settings.no.arg)
|
||
implementation(libs.koin.core)
|
||
api(libs.kmp.observable.viewmodel)
|
||
}
|
||
|
||
all {
|
||
languageSettings.optIn("kotlinx.cinterop.ExperimentalForeignApi")
|
||
languageSettings.optIn("kotlin.experimental.ExperimentalObjCName")
|
||
}
|
||
}
|
||
}
|
||
|
||
sqldelight {
|
||
databases {
|
||
create("ShopDatabase") {
|
||
packageName.set("com.example.minishop.db")
|
||
}
|
||
}
|
||
}
|
||
|
||
android {
|
||
namespace = "com.example.minishop.shared"
|
||
compileSdk = 35
|
||
|
||
compileOptions {
|
||
sourceCompatibility = JavaVersion.VERSION_11
|
||
targetCompatibility = JavaVersion.VERSION_11
|
||
}
|
||
|
||
defaultConfig {
|
||
minSdk = 24
|
||
}
|
||
}
|
||
```
|
||
|
||
## Step 2.2 讲解重点
|
||
### 1)为什么把 SQLDelight 放在 `shared` 模块
|
||
因为数据库访问属于**共享业务层**。
|
||
|
||
这节课我们要做的购物车、订单、商品缓存,
|
||
本质上都不是 Android 独有能力,
|
||
所以应该放在 `shared`,而不是 `composeApp`。
|
||
|
||
### 2)`create("ShopDatabase")` 是什么意思
|
||
这表示 SQLDelight 会生成一个数据库类,名字叫:
|
||
|
||
```kotlin
|
||
ShopDatabase
|
||
```
|
||
|
||
后面 Repository 里就会通过这个类拿到 Queries。
|
||
|
||
### 3)为什么要指定 `packageName`
|
||
因为 SQLDelight 生成的类需要一个明确包名。
|
||
|
||
这里我们统一放到:
|
||
|
||
```kotlin
|
||
com.example.minishop.db
|
||
```
|
||
|
||
这样后面:
|
||
- `DatabaseFactory`
|
||
- `CartRepository`
|
||
- `OrderRepository`
|
||
|
||
都可以围绕这个包来组织。
|
||
|
||
---
|
||
|
||
## Step 2.3:同步 Gradle / 生成 SQLDelight 类
|
||
|
||
### 这一步要做什么
|
||
完成前两步之后,让学生执行一次:
|
||
|
||
1. Sync Gradle
|
||
2. 让项目识别 SQLDelight plugin
|
||
3. 为后面 `.sq` 文件生成代码做好准备
|
||
|
||
### 建议操作
|
||
在 Android Studio 中:
|
||
- 点击 **Sync Project with Gradle Files**
|
||
|
||
如果学生用命令行,可以执行:
|
||
|
||
```bash
|
||
./gradlew tasks
|
||
```
|
||
|
||
或者后续在写完 `.sq` 文件后执行:
|
||
|
||
```bash
|
||
./gradlew :shared:generateSqlDelightInterface
|
||
```
|
||
|
||
## Step 2.3 验收标准
|
||
到这里不需要业务功能已经完成。
|
||
本步的验收只有两个:
|
||
|
||
1. Gradle Sync 不报 SQLDelight plugin 未找到
|
||
2. `shared` 模块已经具备后续写 `.sq` 文件的能力
|
||
|
||
---
|
||
|
||
# 五、本步常见报错与处理
|
||
|
||
## 1)`Plugin [id: 'app.cash.sqldelight'] was not found`
|
||
说明通常是以下原因之一:
|
||
- `libs.versions.toml` 里没有加 `sqldelight` plugin
|
||
- `shared/build.gradle.kts` 没有 `alias(libs.plugins.sqldelight)`
|
||
- Gradle 没有重新 sync
|
||
|
||
## 2)`Unresolved reference: libs.sqldelight.android.driver`
|
||
说明通常是:
|
||
- `libs.versions.toml` 里没有加 library 别名
|
||
- 名字写错
|
||
- 还没同步 Gradle
|
||
|
||
## 3)Android Gradle Plugin 拉取失败
|
||
如果课堂环境里遇到 AGP 版本解析失败,先做这两件事:
|
||
|
||
1. 确认网络能访问 Google Maven
|
||
2. 如果当前项目模板版本过新,统一切到课堂验证通过的稳定版本
|
||
|
||
> 这类问题属于工程环境问题,不是 SQLDelight 本身的问题。
|
||
> 上课时最好提前准备一份已验证可同步的项目基线。
|
||
|
||
---
|
||
|
||
# 六、本步小结
|
||
到这里为止,我们还没有正式开始写购物车表和订单表。
|
||
但已经完成了第7节最重要的起步工作:
|
||
|
||
- 知道为什么第7节必须从 Settings 升级到 SQL
|
||
- 知道 SQLDelight 是什么
|
||
- 知道怎么把 SQLDelight 接进 KMP 项目
|
||
- 知道后面 `.sq` 文件会生成哪些 Kotlin 类
|
||
|
||
接下来下一步,才是正式开始建表:
|
||
|
||
- 购物车表
|
||
- 订单表
|
||
- 订单明细表
|
||
|
||
---
|
||
|
||
# 七、本节整体顺序(重新整理后的主线)
|
||
去掉“离线优先”后,第7节建议严格按下面顺序推进:
|
||
|
||
1. **为什么从 Settings 升级到 SQL**
|
||
2. **接入 SQLDelight**
|
||
3. **建立购物车表 / 订单表 / 订单明细表**
|
||
4. **把 CartRepository 从 Settings 改成 SQL**
|
||
5. **增加 OrderRepository,完成下单闭环**
|
||
6. **在商品列表页落最小 MVI**
|
||
7. **统一错误结构与错误展示**
|
||
8. **课堂验收与课后作业**
|
||
|
||
这样讲的好处是:
|
||
- 先解决“为什么改”
|
||
- 再解决“怎么接技术”
|
||
- 再解决“业务怎么落地”
|
||
- 最后再收状态管理和错误处理
|
||
|
||
---
|
||
|
||
# 八、Step 3:建立购物车表、订单表、订单明细表
|
||
|
||
## 本步目标
|
||
这一部分开始真正进入 SQL 落地。
|
||
完成之后,学生应该能明确三件事:
|
||
|
||
1. 第7节到底要建哪几张表
|
||
2. 每张表分别承担什么业务职责
|
||
3. `.sq` 文件应该放在哪里、怎么写、写完后会生成什么
|
||
|
||
## 这一段先讲什么
|
||
先别急着贴 SQL,先告诉学生:
|
||
|
||
### 为什么第7节至少需要三张表?
|
||
因为本节不是只想把“购物车存起来”,而是要补齐一个最小业务闭环:
|
||
|
||
- 商品加入购物车
|
||
- 购物车生成订单
|
||
- 一个订单包含多条商品项
|
||
|
||
如果只建一张购物车表,后面没法优雅表示订单。
|
||
如果只有订单表,没有订单明细表,后面展示订单内容会很别扭。
|
||
|
||
所以这节课最合理的最小建模是:
|
||
|
||
1. `cart_item`:购物车表
|
||
2. `shop_order`:订单表
|
||
3. `order_item`:订单明细表
|
||
|
||
---
|
||
|
||
## Step 3.1:先讲 SQLDelight 的 `.sq` 文件放哪里
|
||
|
||
### 文件路径规则
|
||
这节课统一放在:
|
||
|
||
```text
|
||
shared/src/commonMain/sqldelight/com/example/minishop/db/
|
||
```
|
||
|
||
### 为什么放这里
|
||
因为:
|
||
- `shared` 是共享业务层
|
||
- `commonMain` 表示 Android / iOS 共用
|
||
- `sqldelight/.../db/` 这一层路径要和我们前面配置的 `packageName` 对应
|
||
|
||
前面在 `shared/build.gradle.kts` 里已经写了:
|
||
|
||
```kotlin
|
||
sqldelight {
|
||
databases {
|
||
create("ShopDatabase") {
|
||
packageName.set("com.example.minishop.db")
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
所以这里的 SQL 文件路径也要围绕这个包来组织。
|
||
|
||
---
|
||
|
||
## Step 3.2:创建购物车表 `Cart.sq`
|
||
|
||
### 购物车表为什么要这些字段
|
||
学生在这里最容易问:
|
||
“为什么购物车表不只存 `productId + quantity`?”
|
||
|
||
课堂上建议这样讲:
|
||
|
||
如果只存 `productId + quantity`,后面每次展示购物车都还要再反查商品信息。
|
||
为了让本节课更顺滑、闭环更完整,这里直接把展示购物车需要的关键字段一起存下来:
|
||
|
||
- `product_id`
|
||
- `title`
|
||
- `price`
|
||
- `image_url`
|
||
- `quantity`
|
||
- `updated_at`
|
||
|
||
这样做的好处:
|
||
- 购物车页展示更直接
|
||
- 后面生成订单明细也更方便
|
||
- 对课堂 demo 更友好
|
||
|
||
### 文件路径
|
||
`shared/src/commonMain/sqldelight/com/example/minishop/db/Cart.sq`
|
||
|
||
### 完整代码
|
||
|
||
```sql
|
||
CREATE TABLE cart_item (
|
||
product_id TEXT NOT NULL PRIMARY KEY,
|
||
title TEXT NOT NULL,
|
||
price REAL NOT NULL,
|
||
image_url TEXT NOT NULL,
|
||
quantity INTEGER NOT NULL,
|
||
updated_at INTEGER NOT NULL
|
||
);
|
||
|
||
selectAll:
|
||
SELECT *
|
||
FROM cart_item
|
||
ORDER BY updated_at DESC;
|
||
|
||
selectById:
|
||
SELECT *
|
||
FROM cart_item
|
||
WHERE product_id = ?;
|
||
|
||
insertOrReplace:
|
||
INSERT OR REPLACE INTO cart_item(
|
||
product_id,
|
||
title,
|
||
price,
|
||
image_url,
|
||
quantity,
|
||
updated_at
|
||
)
|
||
VALUES (?, ?, ?, ?, ?, ?);
|
||
|
||
deleteById:
|
||
DELETE FROM cart_item
|
||
WHERE product_id = ?;
|
||
|
||
deleteAll:
|
||
DELETE FROM cart_item;
|
||
```
|
||
|
||
### 这一段要给学生强调什么
|
||
1. `PRIMARY KEY` 放在 `product_id`
|
||
- 因为一个商品在购物车里只保留一条记录
|
||
2. `INSERT OR REPLACE`
|
||
- 很适合做购物车数量更新
|
||
3. `updated_at`
|
||
- 让购物车列表后面可以按最近修改时间排序
|
||
|
||
### 本步验收
|
||
写完后先不要求页面已经用上。
|
||
只要做到:
|
||
- 文件路径正确
|
||
- SQL 语法正确
|
||
- 能被 SQLDelight 识别
|
||
|
||
---
|
||
|
||
## Step 3.3:创建订单表 `Orders.sq`
|
||
|
||
### 为什么订单要拆成“订单表 + 订单明细表”
|
||
课堂上可以直接讲:
|
||
|
||
一个订单本身是一条业务记录,
|
||
但一个订单里可能有多个商品。
|
||
|
||
所以要拆成:
|
||
- `shop_order`:记录订单本身
|
||
- `order_item`:记录订单里的商品项
|
||
|
||
这就是最常见的一对多关系。
|
||
|
||
### 文件路径
|
||
`shared/src/commonMain/sqldelight/com/example/minishop/db/Orders.sq`
|
||
|
||
### 完整代码
|
||
|
||
```sql
|
||
CREATE TABLE shop_order (
|
||
order_id TEXT NOT NULL PRIMARY KEY,
|
||
total_price REAL NOT NULL,
|
||
status TEXT NOT NULL,
|
||
created_at INTEGER NOT NULL
|
||
);
|
||
|
||
CREATE TABLE order_item (
|
||
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||
order_id TEXT NOT NULL,
|
||
product_id TEXT NOT NULL,
|
||
title TEXT NOT NULL,
|
||
price REAL NOT NULL,
|
||
image_url TEXT NOT NULL,
|
||
quantity INTEGER NOT NULL
|
||
);
|
||
|
||
selectOrders:
|
||
SELECT *
|
||
FROM shop_order
|
||
ORDER BY created_at DESC;
|
||
|
||
insertOrder:
|
||
INSERT INTO shop_order(order_id, total_price, status, created_at)
|
||
VALUES (?, ?, ?, ?);
|
||
|
||
insertOrderItem:
|
||
INSERT INTO order_item(order_id, product_id, title, price, image_url, quantity)
|
||
VALUES (?, ?, ?, ?, ?, ?);
|
||
|
||
selectItemsByOrderId:
|
||
SELECT *
|
||
FROM order_item
|
||
WHERE order_id = ?
|
||
ORDER BY id ASC;
|
||
```
|
||
|
||
### 这一段要给学生强调什么
|
||
1. `shop_order` 记录的是“订单本身”
|
||
2. `order_item` 记录的是“订单中的商品列表”
|
||
3. 本节课先不深讲外键约束、复杂事务、支付状态流转
|
||
4. 先把最小闭环讲清楚最重要
|
||
|
||
### 本步验收
|
||
写完后应当能回答这两个问题:
|
||
- 为什么订单不能只用一张表?
|
||
- 一个订单对应多条商品记录时,为什么要单独建 `order_item`?
|
||
|
||
---
|
||
|
||
## Step 3.4:生成 SQLDelight 代码
|
||
|
||
### 这一步做什么
|
||
当前已经写好了两份 `.sq`:
|
||
- `Cart.sq`
|
||
- `Orders.sq`
|
||
|
||
现在要让 SQLDelight 生成 Kotlin 代码。
|
||
|
||
### 建议操作
|
||
在 Android Studio 中:
|
||
- 重新 Sync Gradle
|
||
|
||
如果用命令行:
|
||
|
||
```bash
|
||
./gradlew :shared:generateSqlDelightInterface
|
||
```
|
||
|
||
### 生成后会出现什么
|
||
后面在 Kotlin 代码里,就可以使用类似这些生成对象:
|
||
|
||
```kotlin
|
||
ShopDatabase
|
||
cartQueries
|
||
ordersQueries
|
||
```
|
||
|
||
> 具体类名会根据 `.sq` 文件内容和 `create("ShopDatabase")` 自动生成。
|
||
|
||
---
|
||
|
||
## Step 3.5:本步常见问题
|
||
|
||
### 1)`.sq` 文件放错目录
|
||
如果学生把文件放到了:
|
||
- `shared/src/commonMain/kotlin/...`
|
||
- 或者少了 `sqldelight/`
|
||
|
||
那 SQLDelight 根本不会识别。
|
||
|
||
### 2)SQL 写了但没有生成类
|
||
检查:
|
||
- 是否已经 Sync Gradle
|
||
- 是否执行过 `generateSqlDelightInterface`
|
||
- `shared/build.gradle.kts` 里是否已有 `sqldelight { ... }`
|
||
|
||
### 3)字段名为什么要用下划线
|
||
例如:
|
||
- `product_id`
|
||
- `image_url`
|
||
- `created_at`
|
||
|
||
课堂上建议统一说明:
|
||
- SQL 层用下划线命名更常见
|
||
- Kotlin 层后面再映射成更顺手的字段名
|
||
|
||
这样学生不会在命名风格上来回打架。
|
||
|
||
---
|
||
|
||
## Step 3.6:本步小结
|
||
到这里,学生已经完成了第7节数据层升级里最关键的一步:
|
||
|
||
- 购物车表建好了
|
||
- 订单表建好了
|
||
- 订单明细表建好了
|
||
- SQLDelight 已经知道要生成哪些 Queries
|
||
|
||
接下来下一步就可以进入真正的 Repository 改造:
|
||
- 把 `CartRepository` 从 Settings 改成 SQL
|
||
- 增加 `OrderRepository`
|
||
|
||
---
|
||
|
||
# 九、Step 4:把 CartRepository 从 Settings 改成 SQL
|
||
|
||
## 本步目标
|
||
这一部分是第7节真正开始“把业务接到 SQL 上”。
|
||
|
||
完成后,学生应该能理解:
|
||
|
||
1. 为什么 Repository 仍然要保留
|
||
2. 为什么不是 UI 直接调用 SQLDelight 生成的 Queries
|
||
3. 购物车从 Settings 切到 SQL 时,哪些代码要一起调整
|
||
|
||
本步会改到这些文件:
|
||
|
||
1. `shared/src/commonMain/kotlin/com/example/minishop/db/DatabaseFactory.kt`
|
||
2. `shared/src/androidMain/kotlin/com/example/minishop/db/AppContext.kt`
|
||
3. `shared/src/androidMain/kotlin/com/example/minishop/db/DatabaseFactory.android.kt`
|
||
4. `shared/src/iosMain/kotlin/com/example/minishop/db/DatabaseFactory.ios.kt`
|
||
5. `shared/src/commonMain/kotlin/com/example/minishop/cart/CartItem.kt`
|
||
6. `shared/src/commonMain/kotlin/com/example/minishop/cart/CartRepository.kt`
|
||
7. `shared/src/commonMain/kotlin/com/example/minishop/cart/CartStorage.kt`
|
||
8. `shared/src/commonMain/kotlin/com/example/minishop/checkout/CheckoutService.kt`
|
||
9. `composeApp/src/androidMain/kotlin/com/example/minishop/MainActivity.kt`
|
||
10. `composeApp/src/androidMain/kotlin/com/example/minishop/ShopViewModel.kt`
|
||
11. `composeApp/src/androidMain/kotlin/com/example/minishop/App.kt`
|
||
|
||
---
|
||
|
||
## Step 4.1:先补数据库入口(DatabaseFactory)
|
||
|
||
### 为什么这一步必须先做
|
||
前面虽然已经写好了 `.sq` 文件,
|
||
但如果没有数据库 driver 和数据库实例入口,`CartRepository` 根本没法拿到:
|
||
|
||
```kotlin
|
||
ShopDatabase
|
||
```
|
||
|
||
所以这一小步不是“附属工作”,而是 SQL 版 Repository 的前置条件。
|
||
|
||
### 文件1:`shared/src/commonMain/kotlin/com/example/minishop/db/DatabaseFactory.kt`
|
||
|
||
```kotlin
|
||
package com.example.minishop.db
|
||
|
||
import app.cash.sqldelight.db.SqlDriver
|
||
|
||
expect class DatabaseFactory {
|
||
fun createDriver(): SqlDriver
|
||
}
|
||
|
||
fun createShopDatabase(factory: DatabaseFactory = DatabaseFactory()): ShopDatabase {
|
||
return ShopDatabase(factory.createDriver())
|
||
}
|
||
```
|
||
|
||
### 文件2:`shared/src/androidMain/kotlin/com/example/minishop/db/AppContext.kt`
|
||
|
||
```kotlin
|
||
package com.example.minishop.db
|
||
|
||
import android.content.Context
|
||
|
||
lateinit var appContext: Context
|
||
private set
|
||
|
||
fun initAppContext(context: Context) {
|
||
appContext = context.applicationContext
|
||
}
|
||
```
|
||
|
||
### 文件3:`shared/src/androidMain/kotlin/com/example/minishop/db/DatabaseFactory.android.kt`
|
||
|
||
```kotlin
|
||
package com.example.minishop.db
|
||
|
||
import app.cash.sqldelight.db.SqlDriver
|
||
import app.cash.sqldelight.driver.android.AndroidSqliteDriver
|
||
|
||
actual class DatabaseFactory {
|
||
actual fun createDriver(): SqlDriver {
|
||
return AndroidSqliteDriver(ShopDatabase.Schema, appContext, "shop.db")
|
||
}
|
||
}
|
||
```
|
||
|
||
### 文件4:`shared/src/iosMain/kotlin/com/example/minishop/db/DatabaseFactory.ios.kt`
|
||
|
||
```kotlin
|
||
package com.example.minishop.db
|
||
|
||
import app.cash.sqldelight.db.SqlDriver
|
||
import app.cash.sqldelight.driver.native.NativeSqliteDriver
|
||
|
||
actual class DatabaseFactory {
|
||
actual fun createDriver(): SqlDriver {
|
||
return NativeSqliteDriver(ShopDatabase.Schema, "shop.db")
|
||
}
|
||
}
|
||
```
|
||
|
||
### 这一段课堂要强调什么
|
||
- `expect / actual` 是 KMP 平台实现差异的典型用法
|
||
- 公共层只关心“我要一个 driver”
|
||
- Android / iOS 各自决定 driver 怎么创建
|
||
|
||
---
|
||
|
||
## Step 4.2:把 `CartItem` 从“极简数量模型”升级成“可展示购物车模型”
|
||
|
||
### 为什么要改 `CartItem`
|
||
第6节的 `CartItem` 只需要:
|
||
- `productId`
|
||
- `quantity`
|
||
|
||
因为当时只是把购物车用 Settings 存起来。
|
||
|
||
但第7节切到 SQL 后,购物车表里已经存了:
|
||
- 标题
|
||
- 单价
|
||
- 图片
|
||
|
||
所以 `CartItem` 也应该升级成更适合 UI 和业务层使用的结构。
|
||
|
||
### 文件路径
|
||
`shared/src/commonMain/kotlin/com/example/minishop/cart/CartItem.kt`
|
||
|
||
### 完整代码
|
||
|
||
```kotlin
|
||
package com.example.minishop.cart
|
||
|
||
data class CartItem(
|
||
val productId: String,
|
||
val quantity: Int,
|
||
val title: String,
|
||
val price: Double,
|
||
val imageUrl: String
|
||
)
|
||
```
|
||
|
||
### 课堂要点
|
||
这里可以顺手提醒学生:
|
||
- SQL 层字段是下划线命名
|
||
- Kotlin 层模型还是 camelCase 更顺手
|
||
- Repository 的职责之一,就是做这种映射
|
||
|
||
---
|
||
|
||
## Step 4.3:把 `CartRepository` 改成 SQL 版
|
||
|
||
### 为什么 Repository 不能删掉
|
||
很多学生会问:
|
||
既然 SQLDelight 已经生成 `cartQueries` 了,为什么不直接在页面里调用?
|
||
|
||
这里要明确讲:
|
||
- UI 不应该直接碰数据库
|
||
- Repository 是数据访问的统一入口
|
||
- 后面如果 SQL 再变、规则再变,上层不用大改
|
||
|
||
### 文件路径
|
||
`shared/src/commonMain/kotlin/com/example/minishop/cart/CartRepository.kt`
|
||
|
||
### 完整代码
|
||
|
||
```kotlin
|
||
package com.example.minishop.cart
|
||
|
||
import com.example.minishop.db.ShopDatabase
|
||
import com.example.minishop.model.Product
|
||
import kotlinx.datetime.Clock
|
||
|
||
class CartRepository(
|
||
private val database: ShopDatabase
|
||
) {
|
||
private val queries = database.cartQueries
|
||
|
||
fun items(): List<CartItem> {
|
||
return queries.selectAll().executeAsList().map {
|
||
CartItem(
|
||
productId = it.product_id,
|
||
quantity = it.quantity.toInt(),
|
||
title = it.title,
|
||
price = it.price,
|
||
imageUrl = it.image_url
|
||
)
|
||
}
|
||
}
|
||
|
||
fun add(product: Product) {
|
||
val current = queries.selectById(product.id).executeAsOneOrNull()
|
||
val nextQuantity = (current?.quantity?.toInt() ?: 0) + 1
|
||
upsert(product, nextQuantity)
|
||
}
|
||
|
||
fun increase(productId: String) {
|
||
val current = queries.selectById(productId).executeAsOneOrNull() ?: return
|
||
queries.insertOrReplace(
|
||
product_id = current.product_id,
|
||
title = current.title,
|
||
price = current.price,
|
||
image_url = current.image_url,
|
||
quantity = current.quantity + 1,
|
||
updated_at = nowMillis()
|
||
)
|
||
}
|
||
|
||
fun decrease(productId: String) {
|
||
val current = queries.selectById(productId).executeAsOneOrNull() ?: return
|
||
val next = current.quantity.toInt() - 1
|
||
if (next <= 0) {
|
||
queries.deleteById(productId)
|
||
} else {
|
||
queries.insertOrReplace(
|
||
product_id = current.product_id,
|
||
title = current.title,
|
||
price = current.price,
|
||
image_url = current.image_url,
|
||
quantity = next.toLong(),
|
||
updated_at = nowMillis()
|
||
)
|
||
}
|
||
}
|
||
|
||
fun remove(productId: String) {
|
||
queries.deleteById(productId)
|
||
}
|
||
|
||
fun clear() {
|
||
queries.deleteAll()
|
||
}
|
||
|
||
private fun upsert(product: Product, quantity: Int) {
|
||
queries.insertOrReplace(
|
||
product_id = product.id,
|
||
title = product.title,
|
||
price = product.price,
|
||
image_url = product.imageUrl,
|
||
quantity = quantity.toLong(),
|
||
updated_at = nowMillis()
|
||
)
|
||
}
|
||
|
||
private fun nowMillis(): Long = Clock.System.now().toEpochMilliseconds()
|
||
}
|
||
```
|
||
|
||
### 这一段课堂要强调什么
|
||
1. `items()` 负责把 SQL 行映射成 `CartItem`
|
||
2. `add(product: Product)` 改成接收整个商品,而不是只传 `productId`
|
||
3. 因为现在购物车表要把展示字段一起存下来
|
||
|
||
---
|
||
|
||
## Step 4.4:旧的 `CartStorage` 怎么处理
|
||
|
||
### 为什么要处理这个文件
|
||
如果这个文件继续保留第6节的序列化实现,
|
||
它会和新的 `CartItem` 结构不一致。
|
||
|
||
所以这一步建议直接改成“保留文件名,但不再承担实际功能”,
|
||
既能让学生知道第6节方案已经退场,
|
||
也不会让项目因为旧代码报错。
|
||
|
||
### 文件路径
|
||
`shared/src/commonMain/kotlin/com/example/minishop/cart/CartStorage.kt`
|
||
|
||
### 完整代码
|
||
|
||
```kotlin
|
||
package com.example.minishop.cart
|
||
|
||
@Deprecated("Lesson 7 switched cart persistence from Settings to SQLDelight")
|
||
class CartStorage
|
||
```
|
||
|
||
### 课堂说明
|
||
你可以直接告诉学生:
|
||
- 第6节它是真的在用
|
||
- 第7节开始它只是“历史痕迹”
|
||
- 这节课的真实购物车持久化已经交给 SQLDelight 了
|
||
|
||
---
|
||
|
||
## Step 4.5:把 `CheckoutService` 改成适配 SQL 版购物车
|
||
|
||
### 为什么这里也要改
|
||
第6节 `CheckoutService` 的总价计算,是通过:
|
||
- `productMap[productId]`
|
||
- 再去拿商品价格
|
||
|
||
但现在 `CartItem` 本身已经有:
|
||
- `price`
|
||
- `title`
|
||
- `imageUrl`
|
||
|
||
所以总价计算就没必要再绕回商品列表。
|
||
|
||
### 文件路径
|
||
`shared/src/commonMain/kotlin/com/example/minishop/checkout/CheckoutService.kt`
|
||
|
||
### 完整代码
|
||
|
||
```kotlin
|
||
package com.example.minishop.checkout
|
||
|
||
import com.example.minishop.cart.CartRepository
|
||
import kotlin.random.Random
|
||
|
||
data class CheckoutResult(
|
||
val success: Boolean,
|
||
val message: String
|
||
)
|
||
|
||
class CheckoutService(
|
||
private val cartRepository: CartRepository
|
||
) {
|
||
fun totalPrice(): Double {
|
||
return cartRepository.items().sumOf { item ->
|
||
item.price * item.quantity
|
||
}
|
||
}
|
||
|
||
fun checkout(): CheckoutResult {
|
||
val total = totalPrice()
|
||
if (total <= 0.0) return CheckoutResult(false, "购物车为空")
|
||
|
||
val success = Random.nextBoolean()
|
||
return if (success) {
|
||
cartRepository.clear()
|
||
CheckoutResult(true, "结算成功(模拟),金额:¥${"%.2f".format(total)}")
|
||
} else {
|
||
CheckoutResult(false, "结算失败(模拟),请重试")
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## Step 4.6:Android 入口补上 `appContext`
|
||
|
||
### 为什么这一步不能漏
|
||
因为 Android 版 `DatabaseFactory` 用到了:
|
||
|
||
```kotlin
|
||
AndroidSqliteDriver(ShopDatabase.Schema, appContext, "shop.db")
|
||
```
|
||
|
||
所以应用启动时必须先初始化 `appContext`。
|
||
|
||
### 文件路径
|
||
`composeApp/src/androidMain/kotlin/com/example/minishop/MainActivity.kt`
|
||
|
||
### 完整代码
|
||
|
||
```kotlin
|
||
package com.example.minishop
|
||
|
||
import android.os.Bundle
|
||
import androidx.activity.ComponentActivity
|
||
import androidx.activity.compose.setContent
|
||
import com.example.minishop.db.initAppContext
|
||
|
||
class MainActivity : ComponentActivity() {
|
||
override fun onCreate(savedInstanceState: Bundle?) {
|
||
super.onCreate(savedInstanceState)
|
||
initAppContext(applicationContext)
|
||
setContent {
|
||
App()
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## Step 4.7:让 `ShopViewModel` 接 SQL 版购物车
|
||
|
||
### 为什么 ViewModel 也得改
|
||
因为 `CartRepository` 的构造方式已经变了:
|
||
- 以前:`CartRepository()`
|
||
- 现在:`CartRepository(database)`
|
||
|
||
并且加购方法也变了:
|
||
- 以前:`add(productId)`
|
||
- 现在:`add(product)`
|
||
|
||
### 文件路径
|
||
`composeApp/src/androidMain/kotlin/com/example/minishop/ShopViewModel.kt`
|
||
|
||
### 完整代码
|
||
|
||
```kotlin
|
||
package com.example.minishop
|
||
|
||
import androidx.compose.runtime.getValue
|
||
import androidx.compose.runtime.mutableStateOf
|
||
import androidx.compose.runtime.setValue
|
||
import androidx.lifecycle.ViewModel
|
||
import com.example.minishop.cart.CartItem
|
||
import com.example.minishop.cart.CartRepository
|
||
import com.example.minishop.checkout.CheckoutService
|
||
import com.example.minishop.db.createShopDatabase
|
||
import com.example.minishop.model.Product
|
||
import com.example.minishop.network.ProductApi
|
||
import com.example.minishop.repository.ProductRepository
|
||
import kotlinx.coroutines.CoroutineScope
|
||
import kotlinx.coroutines.Dispatchers
|
||
import kotlinx.coroutines.SupervisorJob
|
||
import kotlinx.coroutines.cancel
|
||
import kotlinx.coroutines.launch
|
||
|
||
data class ShopUiState(
|
||
val currentTab: Tab = Tab.Home,
|
||
val inDetail: Boolean = false,
|
||
val selectedProductId: String? = null,
|
||
val query: String = "",
|
||
val products: List<Product> = emptyList(),
|
||
val loading: Boolean = false,
|
||
val loadError: String? = null,
|
||
val cartItems: List<CartItem> = emptyList(),
|
||
val totalCount: Int = 0,
|
||
val totalPrice: Double = 0.0
|
||
)
|
||
|
||
class ShopViewModel : ViewModel() {
|
||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||
|
||
private val productRepository = ProductRepository(
|
||
api = ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false)
|
||
)
|
||
private val database = createShopDatabase()
|
||
private val cartRepository = CartRepository(database)
|
||
private val checkoutService = CheckoutService(cartRepository)
|
||
|
||
var uiState by mutableStateOf(ShopUiState())
|
||
private set
|
||
|
||
val filteredProducts: List<Product>
|
||
get() {
|
||
val normalized = uiState.query.trim()
|
||
return if (normalized.isBlank()) {
|
||
uiState.products
|
||
} else {
|
||
uiState.products.filter {
|
||
it.title.contains(normalized, ignoreCase = true) ||
|
||
it.description.contains(normalized, ignoreCase = true)
|
||
}
|
||
}
|
||
}
|
||
|
||
val selectedProduct: Product?
|
||
get() = uiState.products.firstOrNull { it.id == uiState.selectedProductId }
|
||
|
||
init {
|
||
refreshProducts()
|
||
syncCart()
|
||
}
|
||
|
||
fun refreshProducts() {
|
||
scope.launch {
|
||
uiState = uiState.copy(loading = true, loadError = null)
|
||
val list = runCatching { productRepository.getProducts() }
|
||
.onFailure { uiState = uiState.copy(loadError = it.message ?: "加载失败") }
|
||
.getOrDefault(emptyList())
|
||
|
||
uiState = uiState.copy(products = list, loading = false)
|
||
syncCart()
|
||
}
|
||
}
|
||
|
||
fun onQueryChange(value: String) {
|
||
uiState = uiState.copy(query = value)
|
||
}
|
||
|
||
fun selectTab(tab: Tab) {
|
||
uiState = uiState.copy(currentTab = tab)
|
||
}
|
||
|
||
fun openDetail(product: Product) {
|
||
uiState = uiState.copy(inDetail = true, selectedProductId = product.id)
|
||
}
|
||
|
||
fun closeDetail() {
|
||
uiState = uiState.copy(inDetail = false)
|
||
}
|
||
|
||
fun quantityOf(productId: String): Int =
|
||
uiState.cartItems.firstOrNull { it.productId == productId }?.quantity ?: 0
|
||
|
||
fun addToCart(product: Product): String {
|
||
cartRepository.add(product)
|
||
syncCart()
|
||
return "已加入购物车"
|
||
}
|
||
|
||
fun increase(productId: String) {
|
||
cartRepository.increase(productId)
|
||
syncCart()
|
||
}
|
||
|
||
fun decrease(productId: String) {
|
||
cartRepository.decrease(productId)
|
||
syncCart()
|
||
}
|
||
|
||
fun remove(productId: String) {
|
||
cartRepository.remove(productId)
|
||
syncCart()
|
||
}
|
||
|
||
fun clear() {
|
||
cartRepository.clear()
|
||
syncCart()
|
||
}
|
||
|
||
fun checkout(): String {
|
||
val result = checkoutService.checkout()
|
||
syncCart()
|
||
return result.message
|
||
}
|
||
|
||
private fun syncCart() {
|
||
val items = cartRepository.items()
|
||
uiState = uiState.copy(
|
||
cartItems = items,
|
||
totalCount = items.sumOf { it.quantity },
|
||
totalPrice = checkoutService.totalPrice()
|
||
)
|
||
}
|
||
|
||
override fun onCleared() {
|
||
scope.cancel()
|
||
super.onCleared()
|
||
}
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## Step 4.8:让 `App.kt` 使用 SQL 版 `CartItem`
|
||
|
||
### 为什么 UI 这里也要微调
|
||
因为现在购物车项里已经带了:
|
||
- `title`
|
||
- `price`
|
||
|
||
所以购物车页没必要再依赖 `productMap` 才能展示标题和金额。
|
||
|
||
### 这一步课堂建议
|
||
这一段不要整文件重贴,学生太容易淹死。
|
||
你可以只告诉学生改这两处:
|
||
|
||
#### 改动1:商品列表和详情页的加购回调
|
||
把:
|
||
|
||
```kotlin
|
||
vm.addToCart(it.id)
|
||
```
|
||
|
||
改成:
|
||
|
||
```kotlin
|
||
vm.addToCart(it)
|
||
```
|
||
|
||
#### 改动2:购物车页直接使用 `CartItem` 自带字段
|
||
把 `CartScreen` 的参数从:
|
||
|
||
```kotlin
|
||
productMap: Map<String, Product>
|
||
```
|
||
|
||
收掉,改为直接使用:
|
||
- `item.title`
|
||
- `item.price`
|
||
|
||
### 推荐替换后的 `CartScreen`
|
||
|
||
```kotlin
|
||
@Composable
|
||
private fun CartScreen(
|
||
items: List<CartItem>,
|
||
totalPrice: Double,
|
||
onInc: (String) -> Unit,
|
||
onDec: (String) -> Unit,
|
||
onRemove: (String) -> Unit,
|
||
onClear: () -> Unit,
|
||
onCheckout: () -> Unit
|
||
) {
|
||
Box(
|
||
Modifier
|
||
.fillMaxSize()
|
||
.padding(horizontal = 16.dp, vertical = 12.dp)
|
||
) {
|
||
if (items.isEmpty()) {
|
||
EmptyState("购物车为空")
|
||
} else {
|
||
LazyColumn(
|
||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||
contentPadding = PaddingValues(bottom = 96.dp)
|
||
) {
|
||
items(items) { item ->
|
||
Card(Modifier.fillMaxWidth()) {
|
||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||
Text(item.title, fontWeight = FontWeight.Medium)
|
||
Text("¥${formatPrice(item.price * item.quantity)}")
|
||
}
|
||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||
SmallOpButton("-") { onDec(item.productId) }
|
||
Text(" ${item.quantity} ")
|
||
SmallOpButton("+") { onInc(item.productId) }
|
||
Spacer(Modifier.width(8.dp))
|
||
OutlinedButton(onClick = { onRemove(item.productId) }) { Text("移除") }
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
Card(
|
||
modifier = Modifier
|
||
.align(Alignment.BottomCenter)
|
||
.fillMaxWidth(),
|
||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer)
|
||
) {
|
||
Row(
|
||
modifier = Modifier
|
||
.fillMaxWidth()
|
||
.padding(12.dp),
|
||
horizontalArrangement = Arrangement.SpaceBetween,
|
||
verticalAlignment = Alignment.CenterVertically
|
||
) {
|
||
Column {
|
||
Text("总件数:${items.sumOf { it.quantity }}")
|
||
Text("合计:¥${formatPrice(totalPrice)}", fontWeight = FontWeight.Bold)
|
||
}
|
||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||
OutlinedButton(onClick = onClear) { Text("清空") }
|
||
Button(onClick = onCheckout) { Text("结算") }
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## Step 4.9:本步验收
|
||
到这一步,课堂上至少要看到这些结果:
|
||
|
||
- 加购之后,购物车记录来自 SQL 表,而不是 Settings
|
||
- 重启 App 后,购物车数据还能恢复
|
||
- 购物车页能直接显示标题、数量、金额
|
||
- `CartRepository` 已经不再依赖第6节的 `CartStorage`
|
||
|
||
---
|
||
|
||
## Step 4.10:本步小结
|
||
到这里,学生已经完成第7节里第一个真正的数据层升级动作:
|
||
|
||
- SQL 表不是只写着摆设
|
||
- 购物车已经真正切到 SQL
|
||
- UI 仍然通过 Repository 拿数据
|
||
- ViewModel 和页面只是做最小适配
|
||
|
||
接下来下一步,就可以开始新增 `OrderRepository`,把“下单 → 订单列表”闭环接起来。
|
||
|
||
---
|
||
|
||
# 十、本节整体顺序(重新整理后的主线)
|
||
去掉“离线优先”后,第7节建议严格按下面顺序推进:
|
||
|
||
1. **为什么从 Settings 升级到 SQL**
|
||
2. **接入 SQLDelight**
|
||
3. **建立购物车表 / 订单表 / 订单明细表**
|
||
4. **把 CartRepository 从 Settings 改成 SQL**
|
||
5. **增加 OrderRepository,完成下单闭环**
|
||
6. **在商品列表页落最小 MVI**
|
||
7. **统一错误结构与错误展示**
|
||
8. **课堂验收与课后作业**
|
||
|
||
这样讲的好处是:
|
||
- 先解决“为什么改”
|
||
- 再解决“怎么接技术”
|
||
- 再解决“业务怎么落地”
|
||
- 最后再收状态管理和错误处理
|
||
|
||
---
|
||
|
||
# 十一、下一步预告(Step 5)
|
||
下一步开始真正补齐订单闭环:
|
||
|
||
1. 增加 `OrderRepository`
|
||
2. 下单后写入 `shop_order` 和 `order_item`
|
||
3. 清空购物车
|
||
4. 新增订单列表页展示结果
|
||
|
||
并且继续保持本节文档风格:
|
||
- 先讲为什么
|
||
- 再贴官方文档
|
||
- 再给完整代码
|
||
- 再给验收方式
|