docs(ui): provide pure UI full-code handout for classroom copy writing
This commit is contained in:
1 parent
a29d64eb6f
commit
1b002d29c7
1 file changed
+460
-161
+460
-161
@@ -1,201 +1,500 @@
|
|||||||
# 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
|
val productRepository = remember {
|
||||||
|
ProductRepository(
|
||||||
|
api = ProductApi(baseUrl = "https://shopneu.hmos.site/api", useMock = false)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val cartRepository = remember { CartRepository() }
|
||||||
|
val checkoutService = remember { CheckoutService(cartRepository) }
|
||||||
|
|
||||||
```kotlin
|
var currentTab by remember { mutableStateOf(Tab.Home) }
|
||||||
val productRepository = remember {
|
var selected by remember { mutableStateOf<Product?>(null) }
|
||||||
ProductRepository(
|
var inDetail by remember { mutableStateOf(false) }
|
||||||
api = ProductApi(baseUrl = "https://shopneu.hmos.site/api", useMock = false)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
val cartRepository = remember { CartRepository() }
|
|
||||||
val checkoutService = remember { CheckoutService(cartRepository) }
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
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) }
|
||||||
|
|
||||||
## 4. 第三步:加载商品列表
|
fun loadProducts() {
|
||||||
|
scope.launch {
|
||||||
|
loading = true
|
||||||
|
loadError = null
|
||||||
|
val list = runCatching { productRepository.getProducts() }
|
||||||
|
.onFailure { loadError = it.message ?: "加载失败" }
|
||||||
|
.getOrDefault(emptyList())
|
||||||
|
products = list
|
||||||
|
loading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
```kotlin
|
LaunchedEffect(Unit) { loadProducts() }
|
||||||
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) }
|
||||||
|
|
||||||
## 5. 第四步:派生数据
|
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("已加入购物车") }
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
```kotlin
|
currentTab == Tab.Home -> ProductListScreen(
|
||||||
val filteredProducts = remember(products, query) {
|
loading = loading,
|
||||||
val q = query.trim()
|
error = loadError,
|
||||||
if (q.isBlank()) products
|
products = filteredProducts,
|
||||||
else products.filter {
|
totalProducts = products.size,
|
||||||
it.title.contains(q, true) || it.description.contains(q, true)
|
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
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
val cartItems = remember(tick) { cartRepository.items() }
|
else -> CartScreen(
|
||||||
val productMap = remember(products) { products.associateBy { it.id } }
|
items = cartItems,
|
||||||
val totalCount = remember(cartItems) { cartItems.sumOf { it.quantity } }
|
productMap = productMap,
|
||||||
val totalPrice = remember(cartItems, products) { checkoutService.totalPrice(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++ },
|
||||||
## 6. 第五步:Scaffold + 页面切换
|
onCheckout = {
|
||||||
|
val result = checkoutService.checkout(productMap)
|
||||||
```kotlin
|
tick++
|
||||||
Scaffold(
|
scope.launch { snackbarHostState.showSnackbar(result.message) }
|
||||||
topBar = { /* 标题 + 返回 */ },
|
}
|
||||||
bottomBar = { /* Home / Cart */ }
|
)
|
||||||
) { padding ->
|
}
|
||||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
}
|
||||||
when {
|
|
||||||
inDetail -> ProductDetailScreen(...)
|
|
||||||
currentTab == Tab.Home -> ProductListScreen(...)
|
|
||||||
else -> CartScreen(...)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
|
||||||
|
|
||||||
---
|
@Composable
|
||||||
|
private fun ProductListScreen(
|
||||||
## 7. 第六步:首页(两列瀑布流)
|
loading: Boolean,
|
||||||
|
error: String?,
|
||||||
```kotlin
|
products: List<Product>,
|
||||||
LazyVerticalStaggeredGrid(
|
totalProducts: Int,
|
||||||
columns = StaggeredGridCells.Fixed(2),
|
query: String,
|
||||||
verticalItemSpacing = 10.dp,
|
quantityOf: (String) -> Int,
|
||||||
horizontalArrangement = Arrangement.spacedBy(10.dp)
|
onQueryChange: (String) -> Unit,
|
||||||
|
onRetry: () -> Unit,
|
||||||
|
onAdd: (Product) -> Unit,
|
||||||
|
onClick: (Product) -> Unit
|
||||||
) {
|
) {
|
||||||
staggeredItems(filteredProducts, key = { it.id }) { p ->
|
Column(
|
||||||
ElevatedCard(onClick = {
|
Modifier
|
||||||
selected = p
|
.fillMaxSize()
|
||||||
inDetail = true
|
.padding(12.dp),
|
||||||
}) {
|
verticalArrangement = Arrangement.spacedBy(10.dp)
|
||||||
// 图/标题/价格/简介
|
|
||||||
Button(onClick = {
|
|
||||||
cartRepository.add(p.id)
|
|
||||||
tick++
|
|
||||||
}) { Text("加购") }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. 第七步:详情页
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
ProductDetailScreen(
|
|
||||||
product = selected,
|
|
||||||
quantity = selected?.let { p -> cartItems.firstOrNull { it.productId == p.id }?.quantity } ?: 0,
|
|
||||||
onAdd = {
|
|
||||||
cartRepository.add(it.id)
|
|
||||||
tick++
|
|
||||||
}
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 9. 第八步:购物车页 + 固定结算栏
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
Box(Modifier.fillMaxSize()) {
|
|
||||||
LazyColumn(contentPadding = PaddingValues(bottom = 96.dp)) {
|
|
||||||
lazyListItems(cartItems) { item ->
|
|
||||||
// + / - / 移除
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Card(
|
|
||||||
modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth()
|
|
||||||
) {
|
) {
|
||||||
// 总件数、总价、清空、结算
|
OutlinedTextField(
|
||||||
Button(onClick = {
|
modifier = Modifier.fillMaxWidth(),
|
||||||
val msg = checkoutService.checkout(productMap).message
|
value = query,
|
||||||
cartRepository.clear()
|
onValueChange = onQueryChange,
|
||||||
tick++
|
singleLine = true,
|
||||||
}) { Text("结算") }
|
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(
|
||||||
|
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)
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 10. 第九步:图片兜底
|
## 2)补充依赖(如果缺)
|
||||||
|
|
||||||
|
`composeApp/build.gradle.kts` 的 `androidMain.dependencies` 需要有:
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
SubcomposeAsyncImage(
|
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.9.1") // 可有可无,本文档不用
|
||||||
model = url,
|
implementation("io.coil-kt.coil3:coil-compose:3.2.0")
|
||||||
loading = { LocalFallbackImage() },
|
implementation("io.coil-kt.coil3:coil-network-ktor3:3.2.0")
|
||||||
error = { LocalFallbackImage() },
|
|
||||||
success = { SubcomposeAsyncImageContent() }
|
|
||||||
)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 11. 最终验收
|
## 3)你会得到的效果
|
||||||
|
|
||||||
- [ ] 不用 ViewModel 也能跑通列表/详情/购物车/结算
|
- 首页两列瀑布流
|
||||||
- [ ] 两列瀑布流正常
|
- 详情页
|
||||||
- [ ] 底部结算栏固定
|
- 购物车增减删清
|
||||||
- [ ] 图片失败能兜底
|
- 底部固定结算栏
|
||||||
|
- 图片失败本地兜底
|
||||||
---
|
- 全程无 ViewModel
|
||||||
|
|
||||||
## 12. 何时再升级到 ViewModel
|
|
||||||
|
|
||||||
当学员能稳定跑通本版本后,再升级到第7节 MVVM 版:
|
|
||||||
- 把状态从 `App.kt` 挪到 `ShopViewModel`
|
|
||||||
- UI 保留,逻辑搬家
|
|
||||||
Reference in new issue
Block a user