449 lines
13 KiB
Markdown
449 lines
13 KiB
Markdown
# 第1课|KMP Mini Shopping:共享层建模 + 首页/详情页
|
||
|
||
> 课时目标(90~120分钟)
|
||
>
|
||
> 1. 理解 KMP 的分层:`shared` 放业务,`composeApp` 放 Android UI
|
||
> 2. 完成共享业务层(商品、收藏、购物车基础能力)
|
||
> 3. 完成 Android 首页(搜索+列表)与详情页(收藏+加购)
|
||
> 4. Android 端可成功运行
|
||
|
||
---
|
||
|
||
## 一、先讲清楚“为什么这样分层”
|
||
|
||
### 1.1 板书(先讲2分钟)
|
||
|
||
- `shared/commonMain`:业务规则(数据模型、仓库、购物车逻辑)
|
||
- `composeApp/androidMain`:页面展示(Compose)
|
||
|
||
### 1.2 讲解要点(老师可照读)
|
||
|
||
- 今天先不追求“炫 UI”,重点是“共享业务层 + 可运行流程”。
|
||
- 业务代码不写在页面里,后续功能扩展(收藏、购物车、结算)会更稳。
|
||
- 第1课结束标准:**首页、详情、收藏、加购打通**。
|
||
|
||
---
|
||
|
||
## 二、创建项目与基础校验
|
||
|
||
### Step 2.1 创建模板项目
|
||
|
||
使用 KMP Wizard:
|
||
|
||
- Android: 开启
|
||
- iOS: 开启(本课不讲iOS)
|
||
- iOS UI: SwiftUI
|
||
- Include tests: 开启
|
||
|
||
重命名目录为:`kmp-mini-shopping`
|
||
|
||
### Step 2.2 校验项目名与包名
|
||
|
||
`settings.gradle.kts`:
|
||
|
||
```kotlin
|
||
rootProject.name = "kmp-mini-shopping"
|
||
```
|
||
|
||
`composeApp/build.gradle.kts`:
|
||
|
||
```kotlin
|
||
android {
|
||
namespace = "com.example.minishop"
|
||
defaultConfig {
|
||
applicationId = "com.example.minishop"
|
||
}
|
||
}
|
||
```
|
||
|
||
### Step 2.3 课堂提问(互动)
|
||
|
||
- 问:为什么不把 `Product` 直接写在 `App.kt` 里?
|
||
- 目标回答:因为 `Product` 是业务数据模型,应该放在共享层,避免 UI 耦合。
|
||
|
||
---
|
||
|
||
## 三、先完成 shared 业务层(核心)
|
||
|
||
> 路径:`shared/src/commonMain/kotlin/com/example/minishop/`
|
||
|
||
### Step 3.1 新建 `model/Product.kt`
|
||
|
||
```kotlin
|
||
package com.example.minishop.model
|
||
|
||
data class Product(
|
||
val id: String,
|
||
val title: String,
|
||
val price: Double,
|
||
val description: String
|
||
)
|
||
```
|
||
|
||
**讲解**:
|
||
- `id` 是业务唯一标识,不用标题当主键。
|
||
- `price` 用 `Double`,本课先够用。
|
||
|
||
### Step 3.2 新建 `data/ProductRepository.kt`
|
||
|
||
```kotlin
|
||
package com.example.minishop.data
|
||
|
||
import com.example.minishop.model.Product
|
||
|
||
interface ProductRepository {
|
||
fun getProducts(): List<Product>
|
||
fun getProductById(id: String): Product?
|
||
}
|
||
```
|
||
|
||
**讲解**:
|
||
- 先定义“能力接口”,再做实现。
|
||
- 后续替换网络/数据库实现时,UI 层不用大改。
|
||
|
||
### Step 3.3 新建 `data/FakeProductRepository.kt`
|
||
|
||
```kotlin
|
||
package com.example.minishop.data
|
||
|
||
import com.example.minishop.model.Product
|
||
|
||
class FakeProductRepository : ProductRepository {
|
||
private val products = listOf(
|
||
Product("1", "KMP 入门课", 99.0, "跨平台开发基础课程"),
|
||
Product("2", "Compose 实战课", 149.0, "Compose 多端 UI 实战"),
|
||
Product("3", "Kotlin 协程训练营", 129.0, "协程与 Flow 进阶"),
|
||
Product("4", "Clean 架构速成", 199.0, "从0构建可维护架构"),
|
||
Product("5", "SQLDelight 实战", 119.0, "KMP 本地数据库方案"),
|
||
Product("6", "Ktor API 实战", 159.0, "跨平台网络层搭建")
|
||
)
|
||
|
||
override fun getProducts(): List<Product> = products
|
||
|
||
override fun getProductById(id: String): Product? = products.find { it.id == id }
|
||
}
|
||
```
|
||
|
||
**讲解**:
|
||
- `Fake` 的作用是先跑通流程,不被网络问题卡住。
|
||
- 第2课可布置作业:替换为真实 API。
|
||
|
||
### Step 3.4 新建 `data/FavoriteStore.kt`
|
||
|
||
```kotlin
|
||
package com.example.minishop.data
|
||
|
||
class FavoriteStore {
|
||
private val ids = linkedSetOf<String>()
|
||
|
||
fun isFavorite(productId: String): Boolean = ids.contains(productId)
|
||
|
||
fun all(): Set<String> = ids.toSet()
|
||
|
||
fun toggle(productId: String) {
|
||
if (!ids.add(productId)) ids.remove(productId)
|
||
}
|
||
}
|
||
```
|
||
|
||
**讲解**:
|
||
- `toggle` 比 `add/remove` 两套按钮更适合课堂演示。
|
||
- `toSet()` 返回副本,避免外部误改内部状态。
|
||
|
||
### Step 3.5 新建 `cart/CartModels.kt`
|
||
|
||
```kotlin
|
||
package com.example.minishop.cart
|
||
|
||
import com.example.minishop.model.Product
|
||
|
||
data class CartItem(
|
||
val product: Product,
|
||
val quantity: Int
|
||
)
|
||
|
||
data class CartState(
|
||
val items: List<CartItem> = emptyList()
|
||
) {
|
||
val totalCount: Int get() = items.sumOf { it.quantity }
|
||
val totalPrice: Double get() = items.sumOf { it.product.price * it.quantity }
|
||
|
||
fun quantityOf(productId: String): Int =
|
||
items.firstOrNull { it.product.id == productId }?.quantity ?: 0
|
||
}
|
||
```
|
||
|
||
**讲解**:
|
||
- `CartState` 提供“派生数据”(总件数/总价),页面不重复写计算。
|
||
|
||
### Step 3.6 新建 `cart/CartStore.kt`
|
||
|
||
```kotlin
|
||
package com.example.minishop.cart
|
||
|
||
import com.example.minishop.model.Product
|
||
|
||
class CartStore {
|
||
private val mutable = mutableMapOf<String, CartItem>()
|
||
|
||
fun state(): CartState = CartState(mutable.values.sortedBy { it.product.id })
|
||
|
||
fun add(product: Product) {
|
||
val exist = mutable[product.id]
|
||
mutable[product.id] = if (exist == null) CartItem(product, 1) else exist.copy(quantity = exist.quantity + 1)
|
||
}
|
||
|
||
fun increase(productId: String) {
|
||
val item = mutable[productId] ?: return
|
||
mutable[productId] = item.copy(quantity = item.quantity + 1)
|
||
}
|
||
|
||
fun decrease(productId: String) {
|
||
val item = mutable[productId] ?: return
|
||
if (item.quantity <= 1) mutable.remove(productId)
|
||
else mutable[productId] = item.copy(quantity = item.quantity - 1)
|
||
}
|
||
|
||
fun remove(productId: String) {
|
||
mutable.remove(productId)
|
||
}
|
||
|
||
fun clear() {
|
||
mutable.clear()
|
||
}
|
||
}
|
||
```
|
||
|
||
**讲解**:
|
||
- `decrease` 到 0 直接删除,是购物车常见规则。
|
||
- `state()` 统一出口,UI 只读状态,不直接改 map。
|
||
|
||
---
|
||
|
||
## 四、Android 页面:先“首页+详情”打通
|
||
|
||
### Step 4.1 `MainActivity.kt`
|
||
|
||
路径:`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
|
||
|
||
class MainActivity : ComponentActivity() {
|
||
override fun onCreate(savedInstanceState: Bundle?) {
|
||
super.onCreate(savedInstanceState)
|
||
setContent { App() }
|
||
}
|
||
}
|
||
```
|
||
|
||
### Step 4.2 `App.kt`(本课使用“首页+详情版本”)
|
||
|
||
路径:`composeApp/src/androidMain/kotlin/com/example/minishop/App.kt`
|
||
|
||
> 说明:第1课先不加底导航,第2课再扩展为底导航版本。
|
||
|
||
```kotlin
|
||
package com.example.minishop
|
||
|
||
import androidx.compose.foundation.layout.Arrangement
|
||
import androidx.compose.foundation.layout.Box
|
||
import androidx.compose.foundation.layout.Column
|
||
import androidx.compose.foundation.layout.Row
|
||
import androidx.compose.foundation.layout.fillMaxSize
|
||
import androidx.compose.foundation.layout.fillMaxWidth
|
||
import androidx.compose.foundation.layout.padding
|
||
import androidx.compose.foundation.lazy.LazyColumn
|
||
import androidx.compose.foundation.lazy.items
|
||
import androidx.compose.material3.Button
|
||
import androidx.compose.material3.ElevatedCard
|
||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||
import androidx.compose.material3.MaterialTheme
|
||
import androidx.compose.material3.OutlinedButton
|
||
import androidx.compose.material3.OutlinedTextField
|
||
import androidx.compose.material3.Scaffold
|
||
import androidx.compose.material3.Text
|
||
import androidx.compose.material3.TextButton
|
||
import androidx.compose.material3.TopAppBar
|
||
import androidx.compose.runtime.Composable
|
||
import androidx.compose.runtime.getValue
|
||
import androidx.compose.runtime.mutableStateOf
|
||
import androidx.compose.runtime.remember
|
||
import androidx.compose.runtime.setValue
|
||
import androidx.compose.ui.Modifier
|
||
import androidx.compose.ui.unit.dp
|
||
import com.example.minishop.cart.CartStore
|
||
import com.example.minishop.data.FakeProductRepository
|
||
import com.example.minishop.data.FavoriteStore
|
||
import com.example.minishop.model.Product
|
||
|
||
@OptIn(ExperimentalMaterial3Api::class)
|
||
@Composable
|
||
fun App() {
|
||
MaterialTheme {
|
||
val repo = remember { FakeProductRepository() }
|
||
val cartStore = remember { CartStore() }
|
||
val favoriteStore = remember { FavoriteStore() }
|
||
|
||
var selected by remember { mutableStateOf<Product?>(null) }
|
||
var inDetail by remember { mutableStateOf(false) }
|
||
var tick by remember { mutableStateOf(0) }
|
||
var query by remember { mutableStateOf("") }
|
||
|
||
val allProducts = remember { repo.getProducts() }
|
||
val products = remember(query, tick) {
|
||
allProducts.filter {
|
||
it.title.contains(query, ignoreCase = true) ||
|
||
it.description.contains(query, ignoreCase = true)
|
||
}
|
||
}
|
||
|
||
val cartState = remember(tick) { cartStore.state() }
|
||
|
||
Scaffold(
|
||
topBar = {
|
||
TopAppBar(
|
||
title = { Text(if (inDetail) "商品详情" else "Mini Shopping") },
|
||
actions = {
|
||
if (inDetail) {
|
||
TextButton(onClick = { inDetail = false }) { Text("返回") }
|
||
} else {
|
||
Text("购物车(${cartState.totalCount})", modifier = Modifier.padding(end = 12.dp))
|
||
}
|
||
}
|
||
)
|
||
}
|
||
) { padding ->
|
||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||
if (inDetail) {
|
||
ProductDetailScreen(
|
||
product = selected,
|
||
isFavorite = selected?.let { favoriteStore.isFavorite(it.id) } == true,
|
||
onToggleFavorite = {
|
||
selected?.let {
|
||
favoriteStore.toggle(it.id)
|
||
tick++
|
||
}
|
||
},
|
||
onAdd = {
|
||
cartStore.add(it)
|
||
tick++
|
||
}
|
||
)
|
||
} else {
|
||
ProductListScreen(
|
||
products = products,
|
||
query = query,
|
||
onQueryChange = { query = it },
|
||
isFavorite = { favoriteStore.isFavorite(it) },
|
||
quantityOf = { cartState.quantityOf(it) },
|
||
onToggleFavorite = { id ->
|
||
favoriteStore.toggle(id)
|
||
tick++
|
||
},
|
||
onOpen = {
|
||
selected = it
|
||
inDetail = true
|
||
}
|
||
)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
@Composable
|
||
private fun ProductListScreen(
|
||
products: List<Product>,
|
||
query: String,
|
||
onQueryChange: (String) -> Unit,
|
||
isFavorite: (String) -> Boolean,
|
||
quantityOf: (String) -> Int,
|
||
onToggleFavorite: (String) -> Unit,
|
||
onOpen: (Product) -> Unit
|
||
) {
|
||
Column(Modifier.fillMaxSize().padding(12.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||
OutlinedTextField(
|
||
modifier = Modifier.fillMaxWidth(),
|
||
value = query,
|
||
onValueChange = onQueryChange,
|
||
singleLine = true,
|
||
label = { Text("搜索课程") },
|
||
placeholder = { Text("输入标题或描述") }
|
||
)
|
||
|
||
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||
items(products) { p ->
|
||
ElevatedCard(onClick = { onOpen(p) }, modifier = Modifier.fillMaxWidth()) {
|
||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||
Text(p.title, style = MaterialTheme.typography.titleMedium)
|
||
Text("¥${"%.2f".format(p.price)}")
|
||
}
|
||
Text(p.description, style = MaterialTheme.typography.bodySmall)
|
||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||
OutlinedButton(onClick = { onToggleFavorite(p.id) }) {
|
||
Text(if (isFavorite(p.id)) "已收藏" else "收藏")
|
||
}
|
||
val q = quantityOf(p.id)
|
||
if (q > 0) Text("已加购 x$q")
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
@Composable
|
||
private fun ProductDetailScreen(
|
||
product: Product?,
|
||
isFavorite: Boolean,
|
||
onToggleFavorite: () -> Unit,
|
||
onAdd: (Product) -> Unit
|
||
) {
|
||
if (product == null) return
|
||
|
||
Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||
Text(product.title, style = MaterialTheme.typography.headlineSmall)
|
||
Text("价格:¥${"%.2f".format(product.price)}")
|
||
Text(product.description)
|
||
|
||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||
Button(onClick = { onAdd(product) }) { Text("加入购物车") }
|
||
OutlinedButton(onClick = onToggleFavorite) {
|
||
Text(if (isFavorite) "取消收藏" else "收藏")
|
||
}
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 五、本课收尾验收
|
||
|
||
### Step 5.1 构建
|
||
|
||
```bash
|
||
./gradlew :composeApp:assembleDebug
|
||
```
|
||
|
||
### Step 5.2 现场验收点
|
||
|
||
- 能启动应用
|
||
- 首页可搜索
|
||
- 可进入详情
|
||
- 详情可收藏
|
||
- 详情可加入购物车
|
||
- 顶部购物车数量变化
|
||
|
||
### Step 5.3 课后作业
|
||
|
||
- 把“购物车页面”补出来(第2课会讲标准实现)
|
||
|