440 lines
16 KiB
Markdown
440 lines
16 KiB
Markdown
# KMP 两课时课件(底导航增强版)
|
||
|
||
你说得对,购物项目没有底导航不完整。
|
||
这版专门补上 **Android 底部导航(首页/收藏/购物车)+ 详情页**,同学照敲即可完成。
|
||
|
||
---
|
||
|
||
## 一、目标功能(本版)
|
||
|
||
- Android:
|
||
- 底部导航 3 个 Tab:`首页` / `收藏` / `购物车`
|
||
- 首页可搜索商品、收藏、查看已加购数量
|
||
- 详情页可加入购物车/收藏
|
||
- 收藏页可打开详情、加购
|
||
- 购物车页可增减、移除、清空
|
||
- shared:业务代码统一放 `shared/commonMain`
|
||
- iOS:可选做 `TabView`(文末给代码)
|
||
|
||
---
|
||
|
||
## 二、shared 层文件(保持不变)
|
||
|
||
继续使用这 6 个文件:
|
||
|
||
- `model/Product.kt`
|
||
- `data/ProductRepository.kt`
|
||
- `data/FakeProductRepository.kt`
|
||
- `data/FavoriteStore.kt`
|
||
- `cart/CartModels.kt`
|
||
- `cart/CartStore.kt`
|
||
|
||
> 如果你要,我可以把这 6 个文件再单独打包成“发给学生复制粘贴版”。
|
||
|
||
---
|
||
|
||
## 三、Android:替换 `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.material.icons.Icons
|
||
import androidx.compose.material.icons.outlined.Favorite
|
||
import androidx.compose.material.icons.outlined.Home
|
||
import androidx.compose.material.icons.outlined.ShoppingCart
|
||
import androidx.compose.material3.Button
|
||
import androidx.compose.material3.Card
|
||
import androidx.compose.material3.ElevatedCard
|
||
import androidx.compose.material3.Icon
|
||
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 }
|
||
|
||
@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 = { Icon(Icons.Outlined.Home, contentDescription = "首页") },
|
||
label = { Text("首页") }
|
||
)
|
||
NavigationBarItem(
|
||
selected = currentTab == Tab.Favorites,
|
||
onClick = { currentTab = Tab.Favorites },
|
||
icon = { Icon(Icons.Outlined.Favorite, contentDescription = "收藏") },
|
||
label = { Text("收藏(${favorites.size})") }
|
||
)
|
||
NavigationBarItem(
|
||
selected = currentTab == Tab.Cart,
|
||
onClick = { currentTab = Tab.Cart },
|
||
icon = { Icon(Icons.Outlined.ShoppingCart, contentDescription = "购物车") },
|
||
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)
|
||
```
|
||
|
||
---
|
||
|
||
## 四、`composeApp/build.gradle.kts` 确认依赖
|
||
|
||
需要有(用于底导航图标):
|
||
|
||
```kotlin
|
||
commonMain.dependencies {
|
||
implementation(compose.runtime)
|
||
implementation(compose.foundation)
|
||
implementation(compose.material3)
|
||
implementation(compose.ui)
|
||
implementation(compose.components.resources)
|
||
implementation(compose.components.uiToolingPreview)
|
||
implementation(projects.shared)
|
||
}
|
||
```
|
||
|
||
> `material3` 已经包含 `NavigationBar`。图标来自 `material-icons-extended` 时才要额外引;
|
||
> 如果你课堂机器报 icon 不存在,我可以给你一版“纯文字底导航(无 icon)”。
|
||
|
||
---
|
||
|
||
## 五、课堂分步讲解节奏(底导航版)
|
||
|
||
1. 先定义 `Tab` 枚举(Home/Favorites/Cart)
|
||
2. 在 `Scaffold(bottomBar = {})` 里写 `NavigationBar`
|
||
3. 用 `currentTab` 切页面
|
||
4. 再加 `inDetail`(详情页不显示底栏)
|
||
5. 最后接收藏数/购物车数徽标(先用文本)
|
||
|
||
---
|
||
|
||
## 六、iOS 对齐(可选加分):`TabView`
|
||
|
||
如果你要 iOS 也有底导航,`ListView` 外层改成:
|
||
|
||
```swift
|
||
import SwiftUI
|
||
|
||
struct RootTabView: View {
|
||
var body: some View {
|
||
TabView {
|
||
ListView().tabItem {
|
||
Label("首页", systemImage: "house")
|
||
}
|
||
FavoriteListView().tabItem {
|
||
Label("收藏", systemImage: "heart")
|
||
}
|
||
CartView().tabItem {
|
||
Label("购物车", systemImage: "cart")
|
||
}
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
然后 `iOSApp.swift` 里用 `RootTabView()`。
|
||
|
||
---
|
||
|
||
## 七、验收标准(你这门课建议)
|
||
|
||
- [ ] Android 有底导航(3 Tab)
|
||
- [ ] 详情页进入时底栏隐藏,返回后恢复
|
||
- [ ] 收藏数、购物车数会更新
|
||
- [ ] 购物车增减、移除、清空可用
|
||
- [ ] iOS 至少能跑 List + Detail(可选做 TabView)
|
||
|
||
---
|
||
|
||
如果你同意,我下一步直接把**当前项目代码也改成这个底导航版本**(不是只改课件),这样你打开就能演示。
|