275 lines
6.0 KiB
Markdown
275 lines
6.0 KiB
Markdown
# 第6节|KMP 商城:共享层网络与存储(最终版)
|
||
|
||
> 形式:纯讲解 + 现场敲代码 + 课后作业
|
||
> 范围:仅 Android 展示,核心网络/存储全部在 shared
|
||
|
||
---
|
||
|
||
## 1. 本节目标
|
||
|
||
1. 在 `shared/commonMain` 完成商品列表网络加载(Ktor)
|
||
2. 在 `shared/commonMain` 完成购物车持久化(Multiplatform Settings)
|
||
3. Android 页面只调用共享层,不写业务细节
|
||
|
||
---
|
||
|
||
## 2. 依赖配置
|
||
|
||
> 建议放入 `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`
|
||
|
||
```xml
|
||
<uses-permission android:name="android.permission.INTERNET" />
|
||
```
|
||
|
||
---
|
||
|
||
## 3. 共享层代码结构
|
||
|
||
目标目录:
|
||
|
||
```text
|
||
shared/src/commonMain/kotlin/com/example/minishop/
|
||
├─ model/
|
||
├─ network/
|
||
├─ repository/
|
||
├─ cart/
|
||
└─ platform/
|
||
```
|
||
|
||
---
|
||
|
||
## 4. 共享模型
|
||
|
||
### 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. 提交:运行截图 + `commonMain` 核心代码截图
|
||
|