402 lines
15 KiB
Markdown
402 lines
15 KiB
Markdown
# 第2课|KMP Mini Shopping:底导航 + 收藏页 + 购物车页
|
|
|
|
> 课时目标(90~120分钟)
|
|
>
|
|
> 1. 在第1课基础上升级为底导航结构(首页/收藏/购物车)
|
|
> 2. 完成收藏页与购物车页完整闭环
|
|
> 3. 完成课堂验收与常见问题排查
|
|
|
|
---
|
|
|
|
## 一、复习(5分钟)
|
|
|
|
### 1.1 复习问题
|
|
|
|
- 共享层放了哪些文件?
|
|
- 为什么 `CartStore` 不放在 `App.kt` 内部类?
|
|
|
|
### 1.2 目标说明
|
|
|
|
本课只改 `App.kt`,业务层代码沿用第1课。
|
|
|
|
---
|
|
|
|
## 二、替换为“底导航完整版本”
|
|
|
|
路径:`composeApp/src/androidMain/kotlin/com/example/minishop/App.kt`
|
|
|
|
> 将文件整体替换为以下版本。
|
|
|
|
```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.Card
|
|
import androidx.compose.material3.ElevatedCard
|
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
|
import androidx.compose.material3.MaterialTheme
|
|
import androidx.compose.material3.NavigationBar
|
|
import androidx.compose.material3.NavigationBarItem
|
|
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.CartState
|
|
import com.example.minishop.cart.CartStore
|
|
import com.example.minishop.data.FakeProductRepository
|
|
import com.example.minishop.data.FavoriteStore
|
|
import com.example.minishop.model.Product
|
|
|
|
private enum class Tab { Home, Favorites, Cart }
|
|
|
|
@OptIn(ExperimentalMaterial3Api::class)
|
|
@Composable
|
|
fun App() {
|
|
MaterialTheme {
|
|
val repo = remember { FakeProductRepository() }
|
|
val cartStore = remember { CartStore() }
|
|
val favoriteStore = remember { FavoriteStore() }
|
|
|
|
var currentTab by remember { mutableStateOf(Tab.Home) }
|
|
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 favorites = remember(tick) { favoriteStore.all() }
|
|
val cartState = remember(tick) { cartStore.state() }
|
|
|
|
Scaffold(
|
|
topBar = {
|
|
TopAppBar(
|
|
title = {
|
|
Text(
|
|
when {
|
|
inDetail -> "商品详情"
|
|
currentTab == Tab.Home -> "Mini Shopping"
|
|
currentTab == Tab.Favorites -> "收藏夹"
|
|
else -> "购物车"
|
|
}
|
|
)
|
|
},
|
|
actions = {
|
|
if (inDetail) {
|
|
TextButton(onClick = { inDetail = false }) { Text("返回") }
|
|
}
|
|
}
|
|
)
|
|
},
|
|
bottomBar = {
|
|
if (!inDetail) {
|
|
NavigationBar {
|
|
NavigationBarItem(
|
|
selected = currentTab == Tab.Home,
|
|
onClick = { currentTab = Tab.Home },
|
|
icon = { Text("🏠") },
|
|
label = { Text("首页") }
|
|
)
|
|
NavigationBarItem(
|
|
selected = currentTab == Tab.Favorites,
|
|
onClick = { currentTab = Tab.Favorites },
|
|
icon = { Text("❤️") },
|
|
label = { Text("收藏(${favorites.size})") }
|
|
)
|
|
NavigationBarItem(
|
|
selected = currentTab == Tab.Cart,
|
|
onClick = { currentTab = Tab.Cart },
|
|
icon = { Text("🛒") },
|
|
label = { Text("购物车(${cartState.totalCount})") }
|
|
)
|
|
}
|
|
}
|
|
}
|
|
) { padding ->
|
|
Box(Modifier.padding(padding).fillMaxSize()) {
|
|
when {
|
|
inDetail -> ProductDetailScreen(
|
|
product = selected,
|
|
isFavorite = selected?.let { favoriteStore.isFavorite(it.id) } == true,
|
|
onBack = { inDetail = false },
|
|
onToggleFavorite = {
|
|
selected?.let {
|
|
favoriteStore.toggle(it.id)
|
|
tick++
|
|
}
|
|
},
|
|
onAdd = {
|
|
cartStore.add(it)
|
|
tick++
|
|
}
|
|
)
|
|
|
|
currentTab == Tab.Home -> ProductListScreen(
|
|
products = products,
|
|
query = query,
|
|
onQueryChange = { query = it },
|
|
isFavorite = { favoriteStore.isFavorite(it) },
|
|
quantityOf = { cartState.quantityOf(it) },
|
|
onToggleFavorite = { id ->
|
|
favoriteStore.toggle(id)
|
|
tick++
|
|
},
|
|
onClick = {
|
|
selected = it
|
|
inDetail = true
|
|
}
|
|
)
|
|
|
|
currentTab == Tab.Favorites -> FavoriteScreen(
|
|
products = allProducts.filter { favoriteStore.isFavorite(it.id) },
|
|
quantityOf = { cartState.quantityOf(it) },
|
|
onOpen = {
|
|
selected = it
|
|
inDetail = true
|
|
},
|
|
onAdd = {
|
|
cartStore.add(it)
|
|
tick++
|
|
}
|
|
)
|
|
|
|
else -> CartScreen(
|
|
cartState = cartState,
|
|
onInc = { id -> cartStore.increase(id); tick++ },
|
|
onDec = { id -> cartStore.decrease(id); tick++ },
|
|
onRemove = { id -> cartStore.remove(id); tick++ },
|
|
onClear = { cartStore.clear(); tick++ }
|
|
)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
@Composable
|
|
private fun ProductListScreen(
|
|
products: List<Product>,
|
|
query: String,
|
|
onQueryChange: (String) -> Unit,
|
|
isFavorite: (String) -> Boolean,
|
|
quantityOf: (String) -> Int,
|
|
onToggleFavorite: (String) -> Unit,
|
|
onClick: (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("输入标题或描述") }
|
|
)
|
|
|
|
if (products.isEmpty()) {
|
|
EmptyState("没有匹配的商品")
|
|
} else {
|
|
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
|
items(products) { p ->
|
|
ElevatedCard(onClick = { onClick(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("¥${formatPrice(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", style = MaterialTheme.typography.bodySmall)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
@Composable
|
|
private fun ProductDetailScreen(
|
|
product: Product?,
|
|
isFavorite: Boolean,
|
|
onBack: () -> Unit,
|
|
onToggleFavorite: () -> Unit,
|
|
onAdd: (Product) -> Unit
|
|
) {
|
|
if (product == null) {
|
|
EmptyState("商品不存在")
|
|
return
|
|
}
|
|
|
|
Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
|
Text(product.title, style = MaterialTheme.typography.headlineSmall)
|
|
Text("价格:¥${formatPrice(product.price)}")
|
|
Text(product.description)
|
|
|
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
|
Button(onClick = onBack) { Text("返回") }
|
|
Button(onClick = { onAdd(product) }) { Text("加入购物车") }
|
|
OutlinedButton(onClick = onToggleFavorite) {
|
|
Text(if (isFavorite) "取消收藏" else "收藏")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
@Composable
|
|
private fun CartScreen(
|
|
cartState: CartState,
|
|
onInc: (String) -> Unit,
|
|
onDec: (String) -> Unit,
|
|
onRemove: (String) -> Unit,
|
|
onClear: () -> Unit
|
|
) {
|
|
Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
|
if (cartState.items.isNotEmpty()) {
|
|
OutlinedButton(onClick = onClear) { Text("清空购物车") }
|
|
}
|
|
|
|
if (cartState.items.isEmpty()) {
|
|
EmptyState("购物车为空")
|
|
} else {
|
|
LazyColumn(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
|
items(cartState.items) { item ->
|
|
Card(Modifier.fillMaxWidth()) {
|
|
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
|
Text(item.product.title)
|
|
Text("¥${formatPrice(item.product.price * item.quantity)}")
|
|
}
|
|
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
|
OutlinedButton(onClick = { onDec(item.product.id) }) { Text("-") }
|
|
Text("数量 ${item.quantity}")
|
|
OutlinedButton(onClick = { onInc(item.product.id) }) { Text("+") }
|
|
OutlinedButton(onClick = { onRemove(item.product.id) }) { Text("移除") }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
Text("总件数:${cartState.totalCount}")
|
|
Text("合计:¥${formatPrice(cartState.totalPrice)}", style = MaterialTheme.typography.titleMedium)
|
|
}
|
|
}
|
|
}
|
|
|
|
@Composable
|
|
private fun FavoriteScreen(
|
|
products: List<Product>,
|
|
quantityOf: (String) -> Int,
|
|
onOpen: (Product) -> Unit,
|
|
onAdd: (Product) -> Unit
|
|
) {
|
|
if (products.isEmpty()) {
|
|
EmptyState("你还没有收藏课程")
|
|
} else {
|
|
LazyColumn(Modifier.fillMaxSize().padding(16.dp), 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)) {
|
|
Text(p.title, style = MaterialTheme.typography.titleMedium)
|
|
Text("¥${formatPrice(p.price)}")
|
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
|
Button(onClick = { onAdd(p) }) { Text("加入购物车") }
|
|
val q = quantityOf(p.id)
|
|
if (q > 0) Text("已加购 x$q")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
@Composable
|
|
private fun EmptyState(text: String) {
|
|
Box(Modifier.fillMaxSize().padding(24.dp)) {
|
|
Text(text, style = MaterialTheme.typography.bodyLarge)
|
|
}
|
|
}
|
|
|
|
private fun formatPrice(price: Double): String = "%.2f".format(price)
|
|
```
|
|
|
|
---
|
|
|
|
## 三、讲解重点(不要只念代码)
|
|
|
|
### 3.1 底导航为什么放 `Scaffold.bottomBar`
|
|
|
|
- 页面骨架统一在 `Scaffold`
|
|
- 业务切换只改 `currentTab`
|
|
- 详情页通过 `inDetail` 临时覆盖主流程
|
|
|
|
### 3.2 状态管理讲解顺序
|
|
|
|
1. `repo/cartStore/favoriteStore`(业务对象)
|
|
2. `currentTab/selected/inDetail`(页面状态)
|
|
3. `tick`(刷新触发)
|
|
4. `remember(tick)` 推导视图状态
|
|
|
|
### 3.3 课堂提问
|
|
|
|
- 问:为什么收藏数量显示在底导航标签里?
|
|
- 目标回答:这是“状态驱动 UI”,而不是手动 setText。
|
|
|
|
---
|
|
|
|
## 四、本课验收(必须逐项)
|
|
|
|
- 首页:搜索、收藏按钮可用
|
|
- 收藏页:只显示已收藏商品
|
|
- 购物车页:加减、移除、清空可用
|
|
- 详情页:加购/收藏可联动
|
|
- 底导航数字:收藏数量、购物车数量实时变化
|
|
|
|
---
|
|
|
|
## 五、常见错误与修复
|
|
|
|
1. 错误:`TopAppBar experimental`
|
|
- 修复:
|
|
- `import androidx.compose.material3.ExperimentalMaterial3Api`
|
|
- `@OptIn(ExperimentalMaterial3Api::class)`
|
|
|
|
2. 错误:`Unresolved reference: CartStore`
|
|
- 修复:确认 `shared/commonMain` 下 `cart/CartStore.kt` 已创建且 package 正确。
|
|
|
|
3. 错误:页面不刷新
|
|
- 修复:检查修改数据后是否 `tick++`。
|
|
|