# KMP Mini Shopping UI(无 ViewModel|完整可抄代码) > 目标:只讲 UI 写法,不讲 ViewModel。下面给的是可直接粘贴到 `App.kt` 的完整版本。 --- ## 1)直接替换文件 将以下代码完整替换到: `composeApp/src/androidMain/kotlin/com/example/minishop/App.kt` ```kotlin package com.example.minishop import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement 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 enum class Tab { Home, Cart } @OptIn(ExperimentalMaterial3Api::class) @Composable fun App() { MaterialTheme { val scope = rememberCoroutineScope() val snackbarHostState = remember { SnackbarHostState() } val productRepository = remember { ProductRepository( api = ProductApi(baseUrl = "https://shopneu.hmos.site/api", useMock = false) ) } val cartRepository = remember { CartRepository() } val checkoutService = remember { CheckoutService(cartRepository) } var currentTab by remember { mutableStateOf(Tab.Home) } var selected by remember { mutableStateOf(null) } var inDetail by remember { mutableStateOf(false) } var query by remember { mutableStateOf("") } var products by remember { mutableStateOf>(emptyList()) } var loading by remember { mutableStateOf(false) } var loadError by remember { mutableStateOf(null) } var tick by remember { mutableStateOf(0) } fun loadProducts() { scope.launch { loading = true loadError = null val list = runCatching { productRepository.getProducts() } .onFailure { loadError = it.message ?: "加载失败" } .getOrDefault(emptyList()) products = list loading = false } } LaunchedEffect(Unit) { loadProducts() } val normalizedQuery = remember(query) { query.trim() } val filteredProducts = remember(products, normalizedQuery) { if (normalizedQuery.isBlank()) products else products.filter { it.title.contains(normalizedQuery, ignoreCase = true) || it.description.contains(normalizedQuery, ignoreCase = true) } } val cartItems = remember(tick) { cartRepository.items() } val productMap = remember(products) { products.associateBy { it.id } } val totalCount = remember(cartItems) { cartItems.sumOf { it.quantity } } val totalPrice = remember(cartItems, products) { checkoutService.totalPrice(productMap) } Scaffold( snackbarHost = { SnackbarHost(snackbarHostState) }, topBar = { TopAppBar( title = { Text( when { inDetail -> "商品详情" currentTab == Tab.Home -> "KMP Mini Shopping" 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) .fillMaxSize() .background(MaterialTheme.colorScheme.surface) ) { when { inDetail -> ProductDetailScreen( product = selected, quantity = selected?.let { p -> cartItems.firstOrNull { it.productId == p.id }?.quantity } ?: 0, onAdd = { cartRepository.add(it.id) 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 } ) 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) } } ) } } } } } @Composable private fun ProductListScreen( loading: Boolean, error: String?, products: List, 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, productMap: Map, 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( modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer) ) { Row( modifier = Modifier.fillMaxWidth().padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { 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)) if (url.isNotBlank()) { SubcomposeAsyncImage( model = url, contentDescription = null, 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() } ) } 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) ``` --- ## 2)补充依赖(如果缺) `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") ``` --- ## 3)你会得到的效果 - 首页两列瀑布流 - 详情页 - 购物车增减删清 - 底部固定结算栏 - 图片失败本地兜底 - 全程无 ViewModel