docs(ui): provide pure UI full-code handout for classroom copy writing
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled

This commit is contained in:
xiaobai committed 2026-03-04 21:57:11 +08:00
1 parent a29d64eb6f
commit 1b002d29c7
1 file changed
+417 -118
+417 -118
View File
@@ -1,43 +1,87 @@
# KMP Mini Shopping UI 实现指南(Android|无 ViewModel 版) # KMP Mini Shopping UI(无 ViewModel|完整可抄代码)
> 目标:不使用 ViewModel,直接用 `remember + mutableStateOf` 完成 UI。 > 目标:只讲 UI 写法,不讲 ViewModel。下面给的是可直接粘贴到 `App.kt` 的完整版本。
> 适合课堂快速演示或基础班学员先跑通界面与流程。
--- ---
## 1. 文件与前置 ## 1)直接替换文件
文件:`composeApp/src/androidMain/kotlin/com/example/minishop/App.kt` 将以下代码完整替换到:
确保已能访问 shared 层: `composeApp/src/androidMain/kotlin/com/example/minishop/App.kt`
- `ProductRepository`
- `CartRepository`
- `CheckoutService`
---
## 2. 第一步:定义页面状态(App 内)
在 `App()` 内定义:
```kotlin ```kotlin
var currentTab by remember { mutableStateOf(Tab.Home) } package com.example.minishop
var inDetail by remember { mutableStateOf(false) }
var selected by remember { mutableStateOf<Product?>(null) }
var query by remember { mutableStateOf("") } import androidx.compose.foundation.Image
var products by remember { mutableStateOf<List<Product>>(emptyList()) } import androidx.compose.foundation.background
var loading by remember { mutableStateOf(false) } import androidx.compose.foundation.layout.Arrangement
var loadError by remember { mutableStateOf<String?>(null) } import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items as lazyListItems
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items as staggeredItems
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
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.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import coil3.compose.SubcomposeAsyncImage
import coil3.compose.SubcomposeAsyncImageContent
import com.example.minishop.cart.CartItem
import com.example.minishop.cart.CartRepository
import com.example.minishop.checkout.CheckoutService
import com.example.minishop.model.Product
import com.example.minishop.network.ProductApi
import com.example.minishop.repository.ProductRepository
import kotlinx.coroutines.launch
var tick by remember { mutableStateOf(0) } // 强制刷新购物车数据 enum class Tab { Home, Cart }
```
--- @OptIn(ExperimentalMaterial3Api::class)
@Composable
fun App() {
MaterialTheme {
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
## 3. 第二步:初始化 Repository
```kotlin
val productRepository = remember { val productRepository = remember {
ProductRepository( ProductRepository(
api = ProductApi(baseUrl = "https://shopneu.hmos.site/api", useMock = false) api = ProductApi(baseUrl = "https://shopneu.hmos.site/api", useMock = false)
@@ -45,13 +89,17 @@ val productRepository = remember {
} }
val cartRepository = remember { CartRepository() } val cartRepository = remember { CartRepository() }
val checkoutService = remember { CheckoutService(cartRepository) } val checkoutService = remember { CheckoutService(cartRepository) }
```
--- var currentTab by remember { mutableStateOf(Tab.Home) }
var selected by remember { mutableStateOf<Product?>(null) }
var inDetail by remember { mutableStateOf(false) }
## 4. 第三步:加载商品列表 var query by remember { mutableStateOf("") }
var products by remember { mutableStateOf<List<Product>>(emptyList()) }
var loading by remember { mutableStateOf(false) }
var loadError by remember { mutableStateOf<String?>(null) }
var tick by remember { mutableStateOf(0) }
```kotlin
fun loadProducts() { fun loadProducts() {
scope.launch { scope.launch {
loading = true loading = true
@@ -65,18 +113,13 @@ fun loadProducts() {
} }
LaunchedEffect(Unit) { loadProducts() } LaunchedEffect(Unit) { loadProducts() }
```
--- val normalizedQuery = remember(query) { query.trim() }
val filteredProducts = remember(products, normalizedQuery) {
## 5. 第四步:派生数据 if (normalizedQuery.isBlank()) products
```kotlin
val filteredProducts = remember(products, query) {
val q = query.trim()
if (q.isBlank()) products
else products.filter { else products.filter {
it.title.contains(q, true) || it.description.contains(q, true) it.title.contains(normalizedQuery, ignoreCase = true) ||
it.description.contains(normalizedQuery, ignoreCase = true)
} }
} }
@@ -84,118 +127,374 @@ val cartItems = remember(tick) { cartRepository.items() }
val productMap = remember(products) { products.associateBy { it.id } } val productMap = remember(products) { products.associateBy { it.id } }
val totalCount = remember(cartItems) { cartItems.sumOf { it.quantity } } val totalCount = remember(cartItems) { cartItems.sumOf { it.quantity } }
val totalPrice = remember(cartItems, products) { checkoutService.totalPrice(productMap) } val totalPrice = remember(cartItems, products) { checkoutService.totalPrice(productMap) }
```
---
## 6. 第五步:Scaffold + 页面切换
```kotlin
Scaffold( Scaffold(
topBar = { /* 标题 + 返回 */ }, snackbarHost = { SnackbarHost(snackbarHostState) },
bottomBar = { /* Home / Cart */ } topBar = {
) { padding -> TopAppBar(
Box(Modifier.padding(padding).fillMaxSize()) { title = {
Text(
when { when {
inDetail -> ProductDetailScreen(...) inDetail -> "商品详情"
currentTab == Tab.Home -> ProductListScreen(...) currentTab == Tab.Home -> "KMP Mini Shopping"
else -> CartScreen(...) else -> "购物车"
}
)
},
actions = {
if (inDetail) {
TextButton(onClick = { inDetail = false }) { Text("返回") }
} else {
Text(
text = "共 $totalCount 件",
style = MaterialTheme.typography.labelLarge,
modifier = Modifier.padding(end = 12.dp)
)
}
}
)
},
bottomBar = {
if (!inDetail) {
NavigationBar {
NavigationBarItem(
selected = currentTab == Tab.Home,
onClick = { currentTab = Tab.Home },
icon = { Text("🏠") },
label = { Text("商品") }
)
NavigationBarItem(
selected = currentTab == Tab.Cart,
onClick = { currentTab = Tab.Cart },
icon = { Text("🛒") },
label = { Text("购物车($totalCount)") }
)
} }
} }
} }
``` ) { padding ->
Box(
--- Modifier
.padding(padding)
## 7. 第六步:首页(两列瀑布流) .fillMaxSize()
.background(MaterialTheme.colorScheme.surface)
```kotlin
LazyVerticalStaggeredGrid(
columns = StaggeredGridCells.Fixed(2),
verticalItemSpacing = 10.dp,
horizontalArrangement = Arrangement.spacedBy(10.dp)
) { ) {
staggeredItems(filteredProducts, key = { it.id }) { p -> when {
ElevatedCard(onClick = { inDetail -> ProductDetailScreen(
selected = p
inDetail = true
}) {
// 图/标题/价格/简介
Button(onClick = {
cartRepository.add(p.id)
tick++
}) { Text("加购") }
}
}
}
```
---
## 8. 第七步:详情页
```kotlin
ProductDetailScreen(
product = selected, product = selected,
quantity = selected?.let { p -> cartItems.firstOrNull { it.productId == p.id }?.quantity } ?: 0, quantity = selected?.let { p -> cartItems.firstOrNull { it.productId == p.id }?.quantity } ?: 0,
onAdd = { onAdd = {
cartRepository.add(it.id) cartRepository.add(it.id)
tick++ tick++
scope.launch { snackbarHostState.showSnackbar("已加入购物车") }
} }
) )
```
--- currentTab == Tab.Home -> ProductListScreen(
loading = loading,
error = loadError,
products = filteredProducts,
totalProducts = products.size,
query = query,
quantityOf = { id -> cartItems.firstOrNull { it.productId == id }?.quantity ?: 0 },
onQueryChange = { query = it },
onRetry = { loadProducts() },
onAdd = {
cartRepository.add(it.id)
tick++
},
onClick = {
selected = it
inDetail = true
}
)
## 9. 第八步:购物车页 + 固定结算栏 else -> CartScreen(
items = cartItems,
productMap = productMap,
totalPrice = totalPrice,
onInc = { id -> cartRepository.increase(id); tick++ },
onDec = { id -> cartRepository.decrease(id); tick++ },
onRemove = { id -> cartRepository.remove(id); tick++ },
onClear = { cartRepository.clear(); tick++ },
onCheckout = {
val result = checkoutService.checkout(productMap)
tick++
scope.launch { snackbarHostState.showSnackbar(result.message) }
}
)
}
}
}
}
}
```kotlin @Composable
Box(Modifier.fillMaxSize()) { private fun ProductListScreen(
LazyColumn(contentPadding = PaddingValues(bottom = 96.dp)) { loading: Boolean,
lazyListItems(cartItems) { item -> error: String?,
// + / - / 移除 products: List<Product>,
totalProducts: Int,
query: String,
quantityOf: (String) -> Int,
onQueryChange: (String) -> Unit,
onRetry: () -> Unit,
onAdd: (Product) -> 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("输入标题或描述") }
)
Text(
text = "共 $totalProducts 条 · 当前显示 ${products.size} 条",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
when {
loading -> EmptyState("⏳ 加载中...")
error != null -> {
Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer)) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("加载失败:$error", color = MaterialTheme.colorScheme.onErrorContainer)
Button(onClick = onRetry) { Text("重试") }
}
}
}
products.isEmpty() -> EmptyState("没有匹配的商品")
else -> {
LazyVerticalStaggeredGrid(
columns = StaggeredGridCells.Fixed(2),
verticalItemSpacing = 10.dp,
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxSize()
) {
staggeredItems(products, key = { it.id }) { p ->
ElevatedCard(onClick = { onClick(p) }, modifier = Modifier.fillMaxWidth()) {
Column(Modifier.padding(10.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
ProductCover(p.imageUrl)
Text(p.title, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)
PriceTag(p.price)
Text(p.description, style = MaterialTheme.typography.bodySmall, maxLines = 3)
Row(verticalAlignment = Alignment.CenterVertically) {
Button(onClick = { onAdd(p) }) { Text("加购") }
Spacer(Modifier.width(8.dp))
val q = quantityOf(p.id)
if (q > 0) {
Text(text = "x$q", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary)
}
}
}
}
}
}
}
}
}
}
@Composable
private fun ProductDetailScreen(
product: Product?,
quantity: Int,
onAdd: (Product) -> Unit
) {
if (product == null) {
EmptyState("商品不存在")
return
}
Column(
Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Surface(modifier = Modifier.fillMaxWidth(), tonalElevation = 2.dp, shape = RoundedCornerShape(14.dp)) {
Column(Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
ProductCover(product.imageUrl)
Text(product.title, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)
PriceTag(product.price)
Text(product.description)
if (quantity > 0) Text("当前已加购:$quantity", color = MaterialTheme.colorScheme.primary)
}
}
Button(onClick = { onAdd(product) }, modifier = Modifier.fillMaxWidth()) {
Text("加入购物车")
}
}
}
@Composable
private fun CartScreen(
items: List<CartItem>,
productMap: Map<String, Product>,
totalPrice: Double,
onInc: (String) -> Unit,
onDec: (String) -> Unit,
onRemove: (String) -> Unit,
onClear: () -> Unit,
onCheckout: () -> Unit
) {
Box(
Modifier
.fillMaxSize()
.padding(horizontal = 16.dp, vertical = 12.dp)
) {
if (items.isEmpty()) {
EmptyState("购物车为空")
} else {
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp), contentPadding = PaddingValues(bottom = 96.dp)) {
lazyListItems(items) { item ->
val product = productMap[item.productId]
if (product != null) {
Card(Modifier.fillMaxWidth()) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
Text(product.title, fontWeight = FontWeight.Medium)
Text("¥${formatPrice(product.price * item.quantity)}")
}
Row(verticalAlignment = Alignment.CenterVertically) {
SmallOpButton("-") { onDec(product.id) }
Text(" ${item.quantity} ")
SmallOpButton("+") { onInc(product.id) }
Spacer(Modifier.width(8.dp))
OutlinedButton(onClick = { onRemove(product.id) }) { Text("移除") }
}
}
}
}
} }
} }
Card( Card(
modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth() modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth(),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer)
) { ) {
// 总件数、总价、清空、结算 Row(
Button(onClick = { modifier = Modifier.fillMaxWidth().padding(12.dp),
val msg = checkoutService.checkout(productMap).message horizontalArrangement = Arrangement.SpaceBetween,
cartRepository.clear() verticalAlignment = Alignment.CenterVertically
tick++ ) {
}) { Text("结算") } Column {
Text("总件数:${items.sumOf { it.quantity }}")
Text("合计:¥${formatPrice(totalPrice)}", fontWeight = FontWeight.Bold)
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(onClick = onClear) { Text("清空") }
Button(onClick = onCheckout) { Text("结算") }
}
}
}
}
} }
} }
```
--- @Composable
private fun ProductCover(url: String) {
val coverModifier = Modifier
.fillMaxWidth()
.height(150.dp)
.clip(RoundedCornerShape(12.dp))
## 10. 第九步:图片兜底 if (url.isNotBlank()) {
```kotlin
SubcomposeAsyncImage( SubcomposeAsyncImage(
model = url, model = url,
loading = { LocalFallbackImage() }, contentDescription = null,
error = { LocalFallbackImage() }, modifier = coverModifier,
contentScale = ContentScale.Crop,
loading = {
Image(
painter = painterResource(id = R.drawable.course_cover_default),
contentDescription = null,
modifier = coverModifier,
contentScale = ContentScale.Crop
)
},
error = {
Image(
painter = painterResource(id = R.drawable.course_cover_default),
contentDescription = null,
modifier = coverModifier,
contentScale = ContentScale.Crop
)
},
success = { SubcomposeAsyncImageContent() } success = { SubcomposeAsyncImageContent() }
) )
} else {
Image(
painter = painterResource(id = R.drawable.course_cover_default),
contentDescription = null,
modifier = coverModifier,
contentScale = ContentScale.Crop
)
}
}
@Composable
private fun SmallOpButton(text: String, onClick: () -> Unit) {
OutlinedButton(onClick = onClick) { Text(text) }
}
@Composable
private fun PriceTag(price: Double) {
Surface(color = MaterialTheme.colorScheme.primaryContainer, shape = RoundedCornerShape(10.dp)) {
Text(
text = "¥${formatPrice(price)}",
modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp),
color = MaterialTheme.colorScheme.onPrimaryContainer,
fontWeight = FontWeight.SemiBold
)
}
}
@Composable
private fun EmptyState(text: String) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text("🧺", style = MaterialTheme.typography.headlineLarge)
Spacer(Modifier.height(8.dp))
Text(text, style = MaterialTheme.typography.bodyLarge)
}
}
}
private fun formatPrice(price: Double): String = "%.2f".format(price)
``` ```
--- ---
## 11. 最终验收 ## 2)补充依赖(如果缺)
- [ ] 不用 ViewModel 也能跑通列表/详情/购物车/结算 `composeApp/build.gradle.kts` 的 `androidMain.dependencies` 需要有:
- [ ] 两列瀑布流正常
- [ ] 底部结算栏固定 ```kotlin
- [ ] 图片失败能兜底 implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.9.1") // 可有可无,本文档不用
implementation("io.coil-kt.coil3:coil-compose:3.2.0")
implementation("io.coil-kt.coil3:coil-network-ktor3:3.2.0")
```
--- ---
## 12. 何时再升级到 ViewModel ## 3)你会得到的效果
当学员能稳定跑通本版本后,再升级到第7节 MVVM 版: - 首页两列瀑布流
- 把状态从 `App.kt` 挪到 `ShopViewModel` - 详情页
- UI 保留,逻辑搬家 - 购物车增减删清
- 底部固定结算栏
- 图片失败本地兜底
- 全程无 ViewModel