366 lines
14 KiB
Markdown
366 lines
14 KiB
Markdown
# 第2课|KMP Mini Shopping:底导航 + 收藏页 + 购物车(纯讲解版)
|
|
|
|
> 本课目标:
|
|
> 1) 升级为底导航结构;2) 完成收藏页与购物车页;3) 完成课堂验收;4) 留课后作业
|
|
|
|
---
|
|
|
|
## 1. 本课讲解思路
|
|
|
|
在第1课基础上,做“结构升级”而不是“推翻重写”:
|
|
|
|
- 保留 shared 业务层不动
|
|
- 仅升级 `App.kt` 页面组织
|
|
- 用 `Tab + inDetail` 同时管理主流程与详情页
|
|
|
|
---
|
|
|
|
## 2. 替换 `App.kt` 为完整底导航版本
|
|
|
|
路径:`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. 本课运行与作业
|
|
|
|
### 3.1 运行
|
|
|
|
```bash
|
|
./gradlew :composeApp:assembleDebug
|
|
```
|
|
|
|
### 3.2 本课作业
|
|
|
|
1. 购物车页增加“单商品小计”加粗显示。
|
|
2. 收藏页增加“取消收藏”按钮。
|
|
3. 首页底导航图标由 emoji 替换为 Material Icons。
|
|
4. 购物车增加“结算按钮(仅弹提示)”。
|
|
|