删除没用的文档,提交实际用的
This commit is contained in:
1 parent
a12d40f8bb
commit
89ce9eeb2f
11 files changed
+24
-3856
No files matched your search
@@ -1,743 +0,0 @@
|
|||||||
# KMP 两课时教学讲义(群发版|逐步实操)
|
|
||||||
|
|
||||||
> 适用对象:Kotlin Multiplatform 初学者
|
|
||||||
> 教学目标:学生按步骤完成 Android + iOS 的 Mini Shopping 项目并运行
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 0. 统一环境
|
|
||||||
|
|
||||||
- JDK 17
|
|
||||||
- Android Studio(建议最新版稳定版)
|
|
||||||
- Xcode 15+
|
|
||||||
- iOS Simulator 可用
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. 项目创建(统一模板)
|
|
||||||
|
|
||||||
### Step 1.1 打开 KMP Wizard
|
|
||||||
|
|
||||||
访问:
|
|
||||||
|
|
||||||
`https://kmp.jetbrains.com/?android=true&ios=true&iosui=swiftui&includeTests=true`
|
|
||||||
|
|
||||||
### Step 1.2 选择参数
|
|
||||||
|
|
||||||
- Android:开启
|
|
||||||
- iOS:开启
|
|
||||||
- iOS UI:SwiftUI
|
|
||||||
- Include tests:开启
|
|
||||||
|
|
||||||
下载并解压后重命名目录为:
|
|
||||||
|
|
||||||
`kmp-mini-shopping`
|
|
||||||
|
|
||||||
### Step 1.3 统一项目信息
|
|
||||||
|
|
||||||
1. 打开 `settings.gradle.kts`
|
|
||||||
2. 修改:
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
rootProject.name = "kmp-mini-shopping"
|
|
||||||
```
|
|
||||||
|
|
||||||
3. 打开 `composeApp/build.gradle.kts`
|
|
||||||
4. 确认:
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
android {
|
|
||||||
namespace = "com.example.minishop"
|
|
||||||
defaultConfig {
|
|
||||||
applicationId = "com.example.minishop"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. 目录结构目标
|
|
||||||
|
|
||||||
完成后应为:
|
|
||||||
|
|
||||||
```text
|
|
||||||
kmp-mini-shopping/
|
|
||||||
├─ composeApp/
|
|
||||||
│ └─ src/androidMain/kotlin/com/example/minishop/
|
|
||||||
│ ├─ MainActivity.kt
|
|
||||||
│ └─ App.kt
|
|
||||||
├─ shared/
|
|
||||||
│ └─ src/commonMain/kotlin/com/example/minishop/
|
|
||||||
│ ├─ model/
|
|
||||||
│ ├─ data/
|
|
||||||
│ └─ cart/
|
|
||||||
└─ iosApp/
|
|
||||||
```
|
|
||||||
|
|
||||||
说明:
|
|
||||||
- `shared/commonMain`:共享业务代码
|
|
||||||
- `composeApp/androidMain`:Android UI
|
|
||||||
- `iosApp`:iOS SwiftUI
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# 第一课(Android 端完成可运行)
|
|
||||||
|
|
||||||
## 3. 编写 shared 业务层
|
|
||||||
|
|
||||||
在 `shared/src/commonMain/kotlin/com/example/minishop/` 下新建文件。
|
|
||||||
|
|
||||||
### Step 3.1 `model/Product.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.model
|
|
||||||
|
|
||||||
data class Product(
|
|
||||||
val id: String,
|
|
||||||
val title: String,
|
|
||||||
val price: Double,
|
|
||||||
val description: String
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
### Step 3.2 `data/ProductRepository.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.data
|
|
||||||
|
|
||||||
import com.example.minishop.model.Product
|
|
||||||
|
|
||||||
interface ProductRepository {
|
|
||||||
fun getProducts(): List<Product>
|
|
||||||
fun getProductById(id: String): Product?
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Step 3.3 `data/FakeProductRepository.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.data
|
|
||||||
|
|
||||||
import com.example.minishop.model.Product
|
|
||||||
|
|
||||||
class FakeProductRepository : ProductRepository {
|
|
||||||
private val products = listOf(
|
|
||||||
Product("1", "KMP 入门课", 99.0, "跨平台开发基础课程"),
|
|
||||||
Product("2", "Compose 实战课", 149.0, "Compose 多端 UI 实战"),
|
|
||||||
Product("3", "Kotlin 协程训练营", 129.0, "协程与 Flow 进阶"),
|
|
||||||
Product("4", "Clean 架构速成", 199.0, "从0构建可维护架构"),
|
|
||||||
Product("5", "SQLDelight 实战", 119.0, "KMP 本地数据库方案"),
|
|
||||||
Product("6", "Ktor API 实战", 159.0, "跨平台网络层搭建")
|
|
||||||
)
|
|
||||||
|
|
||||||
override fun getProducts(): List<Product> = products
|
|
||||||
|
|
||||||
override fun getProductById(id: String): Product? = products.find { it.id == id }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Step 3.4 `data/FavoriteStore.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.data
|
|
||||||
|
|
||||||
class FavoriteStore {
|
|
||||||
private val ids = linkedSetOf<String>()
|
|
||||||
|
|
||||||
fun isFavorite(productId: String): Boolean = ids.contains(productId)
|
|
||||||
|
|
||||||
fun all(): Set<String> = ids.toSet()
|
|
||||||
|
|
||||||
fun toggle(productId: String) {
|
|
||||||
if (!ids.add(productId)) ids.remove(productId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Step 3.5 `cart/CartModels.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.cart
|
|
||||||
|
|
||||||
import com.example.minishop.model.Product
|
|
||||||
|
|
||||||
data class CartItem(
|
|
||||||
val product: Product,
|
|
||||||
val quantity: Int
|
|
||||||
)
|
|
||||||
|
|
||||||
data class CartState(
|
|
||||||
val items: List<CartItem> = emptyList()
|
|
||||||
) {
|
|
||||||
val totalCount: Int get() = items.sumOf { it.quantity }
|
|
||||||
val totalPrice: Double get() = items.sumOf { it.product.price * it.quantity }
|
|
||||||
|
|
||||||
fun quantityOf(productId: String): Int =
|
|
||||||
items.firstOrNull { it.product.id == productId }?.quantity ?: 0
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Step 3.6 `cart/CartStore.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.cart
|
|
||||||
|
|
||||||
import com.example.minishop.model.Product
|
|
||||||
|
|
||||||
class CartStore {
|
|
||||||
private val mutable = mutableMapOf<String, CartItem>()
|
|
||||||
|
|
||||||
fun state(): CartState = CartState(mutable.values.sortedBy { it.product.id })
|
|
||||||
|
|
||||||
fun add(product: Product) {
|
|
||||||
val exist = mutable[product.id]
|
|
||||||
mutable[product.id] = if (exist == null) CartItem(product, 1) else exist.copy(quantity = exist.quantity + 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun increase(productId: String) {
|
|
||||||
val item = mutable[productId] ?: return
|
|
||||||
mutable[productId] = item.copy(quantity = item.quantity + 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun decrease(productId: String) {
|
|
||||||
val item = mutable[productId] ?: return
|
|
||||||
if (item.quantity <= 1) mutable.remove(productId)
|
|
||||||
else mutable[productId] = item.copy(quantity = item.quantity - 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun remove(productId: String) {
|
|
||||||
mutable.remove(productId)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun clear() {
|
|
||||||
mutable.clear()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Android 入口代码
|
|
||||||
|
|
||||||
### Step 4.1 `composeApp/src/androidMain/kotlin/com/example/minishop/MainActivity.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop
|
|
||||||
|
|
||||||
import android.os.Bundle
|
|
||||||
import androidx.activity.ComponentActivity
|
|
||||||
import androidx.activity.compose.setContent
|
|
||||||
|
|
||||||
class MainActivity : ComponentActivity() {
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
|
||||||
super.onCreate(savedInstanceState)
|
|
||||||
setContent { App() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Step 4.2 `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)
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. 第一课运行验收
|
|
||||||
|
|
||||||
### Step 5.1 Android 构建
|
|
||||||
|
|
||||||
```bash
|
|
||||||
./gradlew :composeApp:assembleDebug
|
|
||||||
```
|
|
||||||
|
|
||||||
### Step 5.2 功能检查
|
|
||||||
|
|
||||||
- 首页能显示商品
|
|
||||||
- 搜索可过滤
|
|
||||||
- 底导航可切换首页/收藏/购物车
|
|
||||||
- 详情可加购、收藏
|
|
||||||
- 购物车支持 + / - / 移除 / 清空
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# 第二课(iOS 接入 shared)
|
|
||||||
|
|
||||||
## 6. iOS 入口与页面
|
|
||||||
|
|
||||||
### Step 6.1 `iosApp/iosApp/iOSApp.swift`
|
|
||||||
|
|
||||||
```swift
|
|
||||||
import SwiftUI
|
|
||||||
|
|
||||||
@main
|
|
||||||
struct iOSApp: App {
|
|
||||||
var body: some Scene {
|
|
||||||
WindowGroup {
|
|
||||||
ListView()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Step 6.2 `iosApp/iosApp/ListView.swift`
|
|
||||||
|
|
||||||
```swift
|
|
||||||
import SwiftUI
|
|
||||||
import Shared
|
|
||||||
|
|
||||||
struct ListView: View {
|
|
||||||
@State private var query: String = ""
|
|
||||||
@State private var tick: Int = 0
|
|
||||||
|
|
||||||
private let repository = FakeProductRepository()
|
|
||||||
private let favoriteStore = FavoriteStore()
|
|
||||||
private let cartStore = CartStore()
|
|
||||||
|
|
||||||
private var products: [Product] {
|
|
||||||
let all = repository.getProducts()
|
|
||||||
guard !query.isEmpty else { return all }
|
|
||||||
return all.filter {
|
|
||||||
$0.title.localizedCaseInsensitiveContains(query) ||
|
|
||||||
$0.description_.localizedCaseInsensitiveContains(query)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
NavigationStack {
|
|
||||||
VStack(spacing: 12) {
|
|
||||||
TextField("搜索课程", text: $query)
|
|
||||||
.textFieldStyle(.roundedBorder)
|
|
||||||
.padding(.horizontal)
|
|
||||||
|
|
||||||
List(products, id: \.id) { product in
|
|
||||||
NavigationLink {
|
|
||||||
DetailView(
|
|
||||||
product: product,
|
|
||||||
favoriteStore: favoriteStore,
|
|
||||||
cartStore: cartStore,
|
|
||||||
onChanged: { tick += 1 }
|
|
||||||
)
|
|
||||||
} label: {
|
|
||||||
VStack(alignment: .leading, spacing: 6) {
|
|
||||||
HStack {
|
|
||||||
Text(product.title).font(.headline)
|
|
||||||
Spacer()
|
|
||||||
Text("¥\(String(format: "%.2f", product.price))")
|
|
||||||
}
|
|
||||||
Text(product.description_)
|
|
||||||
.font(.caption)
|
|
||||||
.foregroundStyle(.secondary)
|
|
||||||
|
|
||||||
HStack(spacing: 8) {
|
|
||||||
Button(favoriteStore.isFavorite(productId: product.id) ? "已收藏" : "收藏") {
|
|
||||||
favoriteStore.toggle(productId: product.id)
|
|
||||||
tick += 1
|
|
||||||
}
|
|
||||||
.buttonStyle(.bordered)
|
|
||||||
|
|
||||||
let q = cartStore.state().quantityOf(productId: product.id)
|
|
||||||
if q > 0 { Text("已加购 x\(q)").font(.caption) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.padding(.vertical, 4)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.navigationTitle("Mini Shopping")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Step 6.3 `iosApp/iosApp/DetailView.swift`
|
|
||||||
|
|
||||||
```swift
|
|
||||||
import SwiftUI
|
|
||||||
import Shared
|
|
||||||
|
|
||||||
struct DetailView: View {
|
|
||||||
let product: Product
|
|
||||||
let favoriteStore: FavoriteStore
|
|
||||||
let cartStore: CartStore
|
|
||||||
let onChanged: () -> Void
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
VStack(alignment: .leading, spacing: 12) {
|
|
||||||
Text(product.title).font(.title2)
|
|
||||||
Text("价格:¥\(String(format: "%.2f", product.price))")
|
|
||||||
Text(product.description_).foregroundStyle(.secondary)
|
|
||||||
|
|
||||||
HStack(spacing: 10) {
|
|
||||||
Button("加入购物车") {
|
|
||||||
cartStore.add(product: product)
|
|
||||||
onChanged()
|
|
||||||
}
|
|
||||||
.buttonStyle(.borderedProminent)
|
|
||||||
|
|
||||||
Button(favoriteStore.isFavorite(productId: product.id) ? "取消收藏" : "收藏") {
|
|
||||||
favoriteStore.toggle(productId: product.id)
|
|
||||||
onChanged()
|
|
||||||
}
|
|
||||||
.buttonStyle(.bordered)
|
|
||||||
}
|
|
||||||
Spacer()
|
|
||||||
}
|
|
||||||
.padding()
|
|
||||||
.navigationTitle("商品详情")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. 第二课运行验收
|
|
||||||
|
|
||||||
### Step 7.1 iOS 运行
|
|
||||||
|
|
||||||
- 打开 `iosApp/iosApp.xcodeproj`
|
|
||||||
- 选择模拟器
|
|
||||||
- 点击 Run
|
|
||||||
|
|
||||||
### Step 7.2 功能检查
|
|
||||||
|
|
||||||
- 列表显示正常
|
|
||||||
- 搜索可用
|
|
||||||
- 详情页可进入
|
|
||||||
- 收藏可切换
|
|
||||||
- 加购后列表可显示数量
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. 常见编译问题(课堂速查)
|
|
||||||
|
|
||||||
1. `TopAppBar ... experimental`
|
|
||||||
- 在 `App.kt` 添加:
|
|
||||||
- `import androidx.compose.material3.ExperimentalMaterial3Api`
|
|
||||||
- `@OptIn(ExperimentalMaterial3Api::class)`
|
|
||||||
|
|
||||||
2. `JAVA_HOME is not set`
|
|
||||||
- 安装 JDK17 并配置环境变量
|
|
||||||
|
|
||||||
3. `Plugin com.android.application not found`
|
|
||||||
- 网络无法访问 Google Maven,检查代理或网络策略
|
|
||||||
|
|
||||||
4. Swift 访问 `description_`
|
|
||||||
- Kotlin 字段 `description` 在 Swift 侧通常映射为 `description_`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 9. 提交要求(学生)
|
|
||||||
|
|
||||||
- 提交目录必须包含:
|
|
||||||
- `shared/commonMain` 的 6 个业务文件
|
|
||||||
- `composeApp/androidMain` 的 `MainActivity.kt` + `App.kt`
|
|
||||||
- `iosApp` 的 `iOSApp.swift` + `ListView.swift` + `DetailView.swift`
|
|
||||||
- 提交说明中写明:
|
|
||||||
- Android 运行截图
|
|
||||||
- iOS 运行截图
|
|
||||||
|
|
||||||
@@ -1,439 +0,0 @@
|
|||||||
# 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)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
如果你同意,我下一步直接把**当前项目代码也改成这个底导航版本**(不是只改课件),这样你打开就能演示。
|
|
||||||
@@ -1,835 +0,0 @@
|
|||||||
# KMP 两课时超详细实操课件(Mini Shopping)
|
|
||||||
|
|
||||||
> 目标:同学们**照着一步一步敲代码**,在两节课内完成一个 Kotlin Multiplatform 项目:
|
|
||||||
>
|
|
||||||
> - Android 端:Compose UI(商品列表 / 详情 / 收藏 / 购物车)
|
|
||||||
> - iOS 端:SwiftUI 页面接入 shared 业务层
|
|
||||||
> - 共享层:`shared/commonMain` 放业务模型与仓库逻辑
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 0. 课前准备(老师提前检查)
|
|
||||||
|
|
||||||
### 0.1 环境版本建议(统一)
|
|
||||||
|
|
||||||
- **JDK**: 17
|
|
||||||
- **Android Studio**: Koala 或更高(建议最新稳定)
|
|
||||||
- **Xcode**: 15+
|
|
||||||
- **Kotlin Multiplatform 插件**:Android Studio 中安装 JetBrains 官方 KMP 插件
|
|
||||||
- **Git**: 任意版本
|
|
||||||
|
|
||||||
### 0.2 课堂统一项目来源(避免结构差异)
|
|
||||||
|
|
||||||
统一让同学从 KMP Wizard 创建:
|
|
||||||
|
|
||||||
- Android: ✅
|
|
||||||
- iOS: ✅
|
|
||||||
- iOS UI: SwiftUI
|
|
||||||
- Include tests: ✅
|
|
||||||
- 模板:Native UI(Compose + SwiftUI)
|
|
||||||
|
|
||||||
> 不同版本 Wizard 生成细节会有差异。只要核心结构一致即可。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. 两课时安排(建议)
|
|
||||||
|
|
||||||
- **第 1 课(90~120 分钟)**:
|
|
||||||
1) 创建 KMP 项目
|
|
||||||
2) 认识目录
|
|
||||||
3) 在 `shared` 写业务模型
|
|
||||||
4) 在 Android 端实现可运行的购物小应用
|
|
||||||
|
|
||||||
- **第 2 课(90~120 分钟)**:
|
|
||||||
1) 完成收藏/购物车完整闭环
|
|
||||||
2) 接入 iOS SwiftUI 到 `shared` 业务层
|
|
||||||
3) 跑通 iOS
|
|
||||||
4) 收尾与常见报错排查
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# 第 1 课:从 0 到 Android 可运行
|
|
||||||
|
|
||||||
## 2. 创建项目
|
|
||||||
|
|
||||||
### 2.1 用 Wizard 下载模板
|
|
||||||
|
|
||||||
打开:<https://kmp.jetbrains.com/?android=true&ios=true&iosui=swiftui&includeTests=true>
|
|
||||||
|
|
||||||
下载后解压,重命名为:
|
|
||||||
|
|
||||||
```text
|
|
||||||
kmp-mini-shopping
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2.2 统一项目名和包名(重要)
|
|
||||||
|
|
||||||
- Project name: `kmp-mini-shopping`
|
|
||||||
- 包名统一:`com.example.minishop`
|
|
||||||
|
|
||||||
在以下位置检查并修改:
|
|
||||||
|
|
||||||
- `settings.gradle.kts`(rootProject.name)
|
|
||||||
- `composeApp/build.gradle.kts`(namespace/applicationId)
|
|
||||||
- kotlin/swift 文件里的 package/import
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. 认识目录(先讲清楚)
|
|
||||||
|
|
||||||
最终我们希望学生看到的核心结构:
|
|
||||||
|
|
||||||
```text
|
|
||||||
kmp-mini-shopping/
|
|
||||||
├─ composeApp/
|
|
||||||
│ └─ src/androidMain/
|
|
||||||
│ ├─ kotlin/com/example/minishop/
|
|
||||||
│ │ ├─ MainActivity.kt
|
|
||||||
│ │ └─ App.kt
|
|
||||||
│ └─ AndroidManifest.xml
|
|
||||||
├─ shared/
|
|
||||||
│ └─ src/commonMain/kotlin/com/example/minishop/
|
|
||||||
│ ├─ model/
|
|
||||||
│ ├─ data/
|
|
||||||
│ └─ cart/
|
|
||||||
└─ iosApp/
|
|
||||||
```
|
|
||||||
|
|
||||||
> 课堂强调:
|
|
||||||
> - `shared/commonMain`:跨平台业务代码
|
|
||||||
> - `composeApp/androidMain`:Android 端 UI
|
|
||||||
> - `iosApp`:iOS SwiftUI
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. 先写 shared 业务层(同学照敲)
|
|
||||||
|
|
||||||
> 在 `shared/src/commonMain/kotlin/com/example/minishop/` 下创建以下文件。
|
|
||||||
|
|
||||||
### 4.1 `model/Product.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.model
|
|
||||||
|
|
||||||
data class Product(
|
|
||||||
val id: String,
|
|
||||||
val title: String,
|
|
||||||
val price: Double,
|
|
||||||
val description: String
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4.2 `data/ProductRepository.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.data
|
|
||||||
|
|
||||||
import com.example.minishop.model.Product
|
|
||||||
|
|
||||||
interface ProductRepository {
|
|
||||||
fun getProducts(): List<Product>
|
|
||||||
fun getProductById(id: String): Product?
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4.3 `data/FakeProductRepository.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.data
|
|
||||||
|
|
||||||
import com.example.minishop.model.Product
|
|
||||||
|
|
||||||
class FakeProductRepository : ProductRepository {
|
|
||||||
private val products = listOf(
|
|
||||||
Product("1", "KMP 入门课", 99.0, "跨平台开发基础课程"),
|
|
||||||
Product("2", "Compose 实战课", 149.0, "Compose 多端 UI 实战"),
|
|
||||||
Product("3", "Kotlin 协程训练营", 129.0, "协程与 Flow 进阶"),
|
|
||||||
Product("4", "Clean 架构速成", 199.0, "从0构建可维护架构"),
|
|
||||||
Product("5", "SQLDelight 实战", 119.0, "KMP 本地数据库方案"),
|
|
||||||
Product("6", "Ktor API 实战", 159.0, "跨平台网络层搭建")
|
|
||||||
)
|
|
||||||
|
|
||||||
override fun getProducts(): List<Product> = products
|
|
||||||
|
|
||||||
override fun getProductById(id: String): Product? = products.find { it.id == id }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4.4 `data/FavoriteStore.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.data
|
|
||||||
|
|
||||||
class FavoriteStore {
|
|
||||||
private val ids = linkedSetOf<String>()
|
|
||||||
|
|
||||||
fun isFavorite(productId: String): Boolean = ids.contains(productId)
|
|
||||||
|
|
||||||
fun all(): Set<String> = ids.toSet()
|
|
||||||
|
|
||||||
fun toggle(productId: String) {
|
|
||||||
if (!ids.add(productId)) ids.remove(productId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4.5 `cart/CartModels.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.cart
|
|
||||||
|
|
||||||
import com.example.minishop.model.Product
|
|
||||||
|
|
||||||
data class CartItem(
|
|
||||||
val product: Product,
|
|
||||||
val quantity: Int
|
|
||||||
)
|
|
||||||
|
|
||||||
data class CartState(
|
|
||||||
val items: List<CartItem> = emptyList()
|
|
||||||
) {
|
|
||||||
val totalCount: Int get() = items.sumOf { it.quantity }
|
|
||||||
val totalPrice: Double get() = items.sumOf { it.product.price * it.quantity }
|
|
||||||
|
|
||||||
fun quantityOf(productId: String): Int =
|
|
||||||
items.firstOrNull { it.product.id == productId }?.quantity ?: 0
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4.6 `cart/CartStore.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.cart
|
|
||||||
|
|
||||||
import com.example.minishop.model.Product
|
|
||||||
|
|
||||||
class CartStore {
|
|
||||||
private val mutable = mutableMapOf<String, CartItem>()
|
|
||||||
|
|
||||||
fun state(): CartState = CartState(mutable.values.sortedBy { it.product.id })
|
|
||||||
|
|
||||||
fun add(product: Product) {
|
|
||||||
val exist = mutable[product.id]
|
|
||||||
mutable[product.id] = if (exist == null) {
|
|
||||||
CartItem(product, 1)
|
|
||||||
} else {
|
|
||||||
exist.copy(quantity = exist.quantity + 1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun increase(productId: String) {
|
|
||||||
val item = mutable[productId] ?: return
|
|
||||||
mutable[productId] = item.copy(quantity = item.quantity + 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun decrease(productId: String) {
|
|
||||||
val item = mutable[productId] ?: return
|
|
||||||
if (item.quantity <= 1) mutable.remove(productId)
|
|
||||||
else mutable[productId] = item.copy(quantity = item.quantity - 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun remove(productId: String) {
|
|
||||||
mutable.remove(productId)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun clear() {
|
|
||||||
mutable.clear()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. 写 Android 端入口
|
|
||||||
|
|
||||||
### 5.1 `composeApp/src/androidMain/kotlin/com/example/minishop/MainActivity.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop
|
|
||||||
|
|
||||||
import android.os.Bundle
|
|
||||||
import androidx.activity.ComponentActivity
|
|
||||||
import androidx.activity.compose.setContent
|
|
||||||
|
|
||||||
class MainActivity : ComponentActivity() {
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
|
||||||
super.onCreate(savedInstanceState)
|
|
||||||
setContent {
|
|
||||||
App()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 5.2 `composeApp/src/androidMain/kotlin/com/example/minishop/App.kt`
|
|
||||||
|
|
||||||
> 这份代码较长,课堂可分四段敲:
|
|
||||||
> 1) App 总控 + 页面枚举
|
|
||||||
> 2) List + Detail
|
|
||||||
> 3) Cart + Favorite
|
|
||||||
> 4) EmptyState + formatPrice
|
|
||||||
|
|
||||||
```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.MaterialTheme
|
|
||||||
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 Screen { List, Detail, Cart, Favorites }
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun App() {
|
|
||||||
MaterialTheme {
|
|
||||||
val repo = remember { FakeProductRepository() }
|
|
||||||
val cartStore = remember { CartStore() }
|
|
||||||
val favoriteStore = remember { FavoriteStore() }
|
|
||||||
|
|
||||||
var screen by remember { mutableStateOf(Screen.List) }
|
|
||||||
var selected by remember { mutableStateOf<Product?>(null) }
|
|
||||||
|
|
||||||
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 (screen) {
|
|
||||||
Screen.List -> "Mini Shopping"
|
|
||||||
Screen.Detail -> "商品详情"
|
|
||||||
Screen.Cart -> "购物车"
|
|
||||||
Screen.Favorites -> "收藏夹"
|
|
||||||
}
|
|
||||||
)
|
|
||||||
},
|
|
||||||
actions = {
|
|
||||||
TextButton(onClick = { screen = Screen.Favorites }) {
|
|
||||||
Text("收藏(${favorites.size})")
|
|
||||||
}
|
|
||||||
TextButton(onClick = { screen = Screen.Cart }) {
|
|
||||||
Text("购物车(${cartState.totalCount})")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
) { padding ->
|
|
||||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
|
||||||
when (screen) {
|
|
||||||
Screen.List -> ProductListScreen(
|
|
||||||
products = products,
|
|
||||||
query = query,
|
|
||||||
onQueryChange = { query = it },
|
|
||||||
isFavorite = { favoriteStore.isFavorite(it) },
|
|
||||||
quantityOf = { cartState.quantityOf(it) },
|
|
||||||
onToggleFavorite = {
|
|
||||||
favoriteStore.toggle(it)
|
|
||||||
tick++
|
|
||||||
},
|
|
||||||
onClick = {
|
|
||||||
selected = it
|
|
||||||
screen = Screen.Detail
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
Screen.Detail -> ProductDetailScreen(
|
|
||||||
product = selected,
|
|
||||||
isFavorite = selected?.let { favoriteStore.isFavorite(it.id) } == true,
|
|
||||||
onBack = { screen = Screen.List },
|
|
||||||
onToggleFavorite = {
|
|
||||||
selected?.let {
|
|
||||||
favoriteStore.toggle(it.id)
|
|
||||||
tick++
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onAdd = {
|
|
||||||
cartStore.add(it)
|
|
||||||
tick++
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
Screen.Cart -> CartScreen(
|
|
||||||
cartState = cartState,
|
|
||||||
onBack = { screen = Screen.List },
|
|
||||||
onInc = { id -> cartStore.increase(id); tick++ },
|
|
||||||
onDec = { id -> cartStore.decrease(id); tick++ },
|
|
||||||
onRemove = { id -> cartStore.remove(id); tick++ },
|
|
||||||
onClear = { cartStore.clear(); tick++ }
|
|
||||||
)
|
|
||||||
|
|
||||||
Screen.Favorites -> FavoriteScreen(
|
|
||||||
products = allProducts.filter { favoriteStore.isFavorite(it.id) },
|
|
||||||
quantityOf = { cartState.quantityOf(it) },
|
|
||||||
onBack = { screen = Screen.List },
|
|
||||||
onOpen = {
|
|
||||||
selected = it
|
|
||||||
screen = Screen.Detail
|
|
||||||
},
|
|
||||||
onAdd = {
|
|
||||||
cartStore.add(it)
|
|
||||||
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,
|
|
||||||
onBack: () -> Unit,
|
|
||||||
onInc: (String) -> Unit,
|
|
||||||
onDec: (String) -> Unit,
|
|
||||||
onRemove: (String) -> Unit,
|
|
||||||
onClear: () -> Unit
|
|
||||||
) {
|
|
||||||
Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
|
||||||
Button(onClick = onBack) { Text("返回列表") }
|
|
||||||
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,
|
|
||||||
onBack: () -> Unit,
|
|
||||||
onOpen: (Product) -> Unit,
|
|
||||||
onAdd: (Product) -> Unit
|
|
||||||
) {
|
|
||||||
Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
|
||||||
Button(onClick = onBack) { Text("返回列表") }
|
|
||||||
if (products.isEmpty()) {
|
|
||||||
EmptyState("你还没有收藏课程")
|
|
||||||
} else {
|
|
||||||
LazyColumn(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)
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Android 运行验证(第 1 课结束前)
|
|
||||||
|
|
||||||
### 6.1 执行
|
|
||||||
|
|
||||||
```bash
|
|
||||||
./gradlew :composeApp:assembleDebug
|
|
||||||
```
|
|
||||||
|
|
||||||
或在 Android Studio 点击 Run。
|
|
||||||
|
|
||||||
### 6.2 验收点(老师逐条检查)
|
|
||||||
|
|
||||||
- 能看到商品列表
|
|
||||||
- 搜索框可过滤
|
|
||||||
- 点击“收藏”顶部数字变化
|
|
||||||
- 详情页“加入购物车”后,顶部购物车数量变化
|
|
||||||
- 购物车可 + / - / 移除 / 清空
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# 第 2 课:iOS 接入 shared 业务层 + 完整联调
|
|
||||||
|
|
||||||
## 7. 为什么 iOS 也能用 shared
|
|
||||||
|
|
||||||
- `shared/commonMain` 是 Kotlin 多平台共享代码
|
|
||||||
- iOS 侧可通过 `Shared` framework 直接调用 Kotlin 类
|
|
||||||
- 所以 SwiftUI 页面可以直接 new:
|
|
||||||
- `FakeProductRepository()`
|
|
||||||
- `FavoriteStore()`
|
|
||||||
- `CartStore()`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. 改 iOS 代码(同学照敲)
|
|
||||||
|
|
||||||
### 8.1 `iosApp/iosApp/iOSApp.swift`
|
|
||||||
|
|
||||||
```swift
|
|
||||||
import SwiftUI
|
|
||||||
|
|
||||||
@main
|
|
||||||
struct iOSApp: App {
|
|
||||||
var body: some Scene {
|
|
||||||
WindowGroup {
|
|
||||||
ListView()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 8.2 `iosApp/iosApp/ListView.swift`
|
|
||||||
|
|
||||||
```swift
|
|
||||||
import SwiftUI
|
|
||||||
import Shared
|
|
||||||
|
|
||||||
struct ListView: View {
|
|
||||||
@State private var query: String = ""
|
|
||||||
@State private var tick: Int = 0
|
|
||||||
|
|
||||||
private let repository = FakeProductRepository()
|
|
||||||
private let favoriteStore = FavoriteStore()
|
|
||||||
private let cartStore = CartStore()
|
|
||||||
|
|
||||||
private var products: [Product] {
|
|
||||||
let all = repository.getProducts()
|
|
||||||
guard !query.isEmpty else { return all }
|
|
||||||
return all.filter {
|
|
||||||
$0.title.localizedCaseInsensitiveContains(query) ||
|
|
||||||
$0.description_.localizedCaseInsensitiveContains(query)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
NavigationStack {
|
|
||||||
VStack(spacing: 12) {
|
|
||||||
TextField("搜索课程", text: $query)
|
|
||||||
.textFieldStyle(.roundedBorder)
|
|
||||||
.padding(.horizontal)
|
|
||||||
|
|
||||||
List(products, id: \.id) { product in
|
|
||||||
NavigationLink {
|
|
||||||
DetailView(
|
|
||||||
product: product,
|
|
||||||
favoriteStore: favoriteStore,
|
|
||||||
cartStore: cartStore,
|
|
||||||
onChanged: { tick += 1 }
|
|
||||||
)
|
|
||||||
} label: {
|
|
||||||
VStack(alignment: .leading, spacing: 6) {
|
|
||||||
HStack {
|
|
||||||
Text(product.title)
|
|
||||||
.font(.headline)
|
|
||||||
Spacer()
|
|
||||||
Text("¥\(String(format: "%.2f", product.price))")
|
|
||||||
.font(.subheadline)
|
|
||||||
}
|
|
||||||
|
|
||||||
Text(product.description_)
|
|
||||||
.font(.caption)
|
|
||||||
.foregroundStyle(.secondary)
|
|
||||||
|
|
||||||
HStack(spacing: 8) {
|
|
||||||
Button(favoriteStore.isFavorite(productId: product.id) ? "已收藏" : "收藏") {
|
|
||||||
favoriteStore.toggle(productId: product.id)
|
|
||||||
tick += 1
|
|
||||||
}
|
|
||||||
.buttonStyle(.bordered)
|
|
||||||
|
|
||||||
let q = cartStore.state().quantityOf(productId: product.id)
|
|
||||||
if q > 0 {
|
|
||||||
Text("已加购 x\(q)")
|
|
||||||
.font(.caption)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.padding(.vertical, 4)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.navigationTitle("Mini Shopping")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 8.3 `iosApp/iosApp/DetailView.swift`
|
|
||||||
|
|
||||||
```swift
|
|
||||||
import SwiftUI
|
|
||||||
import Shared
|
|
||||||
|
|
||||||
struct DetailView: View {
|
|
||||||
let product: Product
|
|
||||||
let favoriteStore: FavoriteStore
|
|
||||||
let cartStore: CartStore
|
|
||||||
let onChanged: () -> Void
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
VStack(alignment: .leading, spacing: 12) {
|
|
||||||
Text(product.title)
|
|
||||||
.font(.title2)
|
|
||||||
|
|
||||||
Text("价格:¥\(String(format: "%.2f", product.price))")
|
|
||||||
.font(.headline)
|
|
||||||
|
|
||||||
Text(product.description_)
|
|
||||||
.foregroundStyle(.secondary)
|
|
||||||
|
|
||||||
HStack(spacing: 10) {
|
|
||||||
Button("加入购物车") {
|
|
||||||
cartStore.add(product: product)
|
|
||||||
onChanged()
|
|
||||||
}
|
|
||||||
.buttonStyle(.borderedProminent)
|
|
||||||
|
|
||||||
Button(favoriteStore.isFavorite(productId: product.id) ? "取消收藏" : "收藏") {
|
|
||||||
favoriteStore.toggle(productId: product.id)
|
|
||||||
onChanged()
|
|
||||||
}
|
|
||||||
.buttonStyle(.bordered)
|
|
||||||
}
|
|
||||||
|
|
||||||
Spacer()
|
|
||||||
}
|
|
||||||
.padding()
|
|
||||||
.navigationTitle("商品详情")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 9. iOS 运行验证
|
|
||||||
|
|
||||||
### 9.1 在 Xcode 打开
|
|
||||||
|
|
||||||
- 打开 `iosApp/iosApp.xcodeproj`
|
|
||||||
- 选择 iOS Simulator(如 iPhone 15)
|
|
||||||
- Run
|
|
||||||
|
|
||||||
### 9.2 验收点
|
|
||||||
|
|
||||||
- 能看到商品列表
|
|
||||||
- 搜索可过滤
|
|
||||||
- 详情可进入
|
|
||||||
- 收藏按钮可切换
|
|
||||||
- 加入购物车后返回列表显示“已加购 xN”
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 10. 课堂常见报错速查
|
|
||||||
|
|
||||||
### 报错 A:`Plugin com.android.application not found`
|
|
||||||
|
|
||||||
原因:拉不到 Google Maven(网络/代理/TLS)。
|
|
||||||
|
|
||||||
排查:
|
|
||||||
1. 能否访问 `https://dl.google.com/dl/android/maven2/`
|
|
||||||
2. `settings.gradle.kts` 里 `pluginManagement.repositories` 是否有 `google()`
|
|
||||||
3. 代理是否污染 TLS
|
|
||||||
|
|
||||||
### 报错 B:`JAVA_HOME is not set`
|
|
||||||
|
|
||||||
```bash
|
|
||||||
java -version
|
|
||||||
javac -version
|
|
||||||
```
|
|
||||||
|
|
||||||
确认 JDK17 后设置环境变量。
|
|
||||||
|
|
||||||
### 报错 C:Swift 里字段名访问异常(如 description)
|
|
||||||
|
|
||||||
Kotlin `description` 在 Swift 侧可能映射成 `description_`,按实际自动补全为准。
|
|
||||||
|
|
||||||
### 报错 D:找不到 Shared 类型
|
|
||||||
|
|
||||||
先在 Android Studio 同步 Gradle,再回 Xcode Clean Build Folder + Run。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 11. 课后作业(可选)
|
|
||||||
|
|
||||||
1. 新增“分类筛选”(全部/入门/进阶)
|
|
||||||
2. 购物车增加“优惠券”逻辑(满减)
|
|
||||||
3. 数据改为 Ktor + 本地缓存(仍在 shared)
|
|
||||||
4. iOS 增加购物车页与收藏页(与 Android 对齐)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 12. 教学口令(老师照读)
|
|
||||||
|
|
||||||
- “先写 shared,再写平台 UI,这是 KMP 思维。”
|
|
||||||
- “业务逻辑不跟 UI 耦合,Android 和 iOS 都吃同一份逻辑。”
|
|
||||||
- “今天不是做炫技 UI,是把跨平台分层打通。”
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 13. 最终验收清单(老师打勾)
|
|
||||||
|
|
||||||
- [ ] 项目能同步 Gradle
|
|
||||||
- [ ] Android 能启动并完整走通列表/详情/收藏/购物车
|
|
||||||
- [ ] `shared/commonMain` 包含 model/data/cart 代码
|
|
||||||
- [ ] iOS SwiftUI 能调用 shared 类型并运行
|
|
||||||
- [ ] 同学能解释为什么 shared 不一定要有 androidMain
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
如果你要,我可以在下一版再给你补一份:
|
|
||||||
|
|
||||||
1) **“课堂投屏版”**(更短、每 10 分钟一页)
|
|
||||||
2) **“助教检查清单版”**(按文件对照逐项验收)
|
|
||||||
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
# Mini Shopping 文档索引(课堂使用)
|
|
||||||
|
|
||||||
## 当前推荐(第6-7节)
|
|
||||||
|
|
||||||
1. `第6_7节课程大纲_确认版.md`
|
|
||||||
- 内容:你最终确认的第6/7节课程大纲(原文固定版)
|
|
||||||
|
|
||||||
2. `第6节_共享层网络与存储_最终版.md`
|
|
||||||
- 内容:第6节实操讲稿(按步骤写完可跑通网络+持久化)
|
|
||||||
|
|
||||||
3. `第7节_整合与结业实战_最终版.md`
|
|
||||||
- 内容:第7节实操讲稿(MVVM重构+全流程整合)
|
|
||||||
|
|
||||||
4. `UI_参考资料_Android.md`
|
|
||||||
- 内容:Android UI 逐步照写指南(从 0 到完整页面)
|
|
||||||
|
|
||||||
5. `UI_参考资料_Android_无ViewModel.md`
|
|
||||||
- 内容:Android UI 无 ViewModel 版本(remember/mutableStateOf 直写)
|
|
||||||
|
|
||||||
6. `UI_纯UI离线版_Android.md`
|
|
||||||
- 内容:纯 UI 离线版完整代码(不走网络、不用 ViewModel)
|
|
||||||
|
|
||||||
7. `第6_7节课程大纲_KMP商城_网络存储与整合.md`
|
|
||||||
- 内容:第6-7节目标、节奏、产出、SkillMap映射
|
|
||||||
|
|
||||||
## 归档文档(历史版本)
|
|
||||||
|
|
||||||
- `第1课_KMP_MiniShopping_共享层与首页详情.md`
|
|
||||||
- `第2课_KMP_MiniShopping_底导航收藏购物车.md`
|
|
||||||
- `KMP_两课时教学讲稿_MiniShopping_超详细实操版.md`
|
|
||||||
- `KMP_两课时教学讲稿_MiniShopping_底导航增强版.md`
|
|
||||||
- `KMP_两课时教学讲义_群发版_逐步实操.md`
|
|
||||||
|
|
||||||
@@ -1,410 +0,0 @@
|
|||||||
# KMP Mini Shopping UI 实现指南(Android|逐步照写版)
|
|
||||||
|
|
||||||
> 目标:这份文档按“最小可运行 -> 完整效果”拆到每一步。学员照着写即可完成 UI。
|
|
||||||
> 前置:`ShopViewModel` 已存在(第7节已完成)。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 0. 准备(先不写业务)
|
|
||||||
|
|
||||||
### 0.1 打开文件
|
|
||||||
|
|
||||||
- `composeApp/src/androidMain/kotlin/com/example/minishop/App.kt`
|
|
||||||
|
|
||||||
### 0.2 先放最小 App 骨架(确认可编译)
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop
|
|
||||||
|
|
||||||
import androidx.compose.runtime.Composable
|
|
||||||
import androidx.compose.material3.Text
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun App() {
|
|
||||||
Text("Mini Shopping")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
先 Run 一次,确认 App 能起来。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. 第一步:搭 Scaffold 壳子(顶栏 + 底栏 + 内容区)
|
|
||||||
|
|
||||||
把 `App()` 改成下面:
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
@Composable
|
|
||||||
fun App() {
|
|
||||||
val vm: ShopViewModel = androidx.lifecycle.viewmodel.compose.viewModel()
|
|
||||||
val ui = vm.uiState
|
|
||||||
|
|
||||||
androidx.compose.material3.MaterialTheme {
|
|
||||||
androidx.compose.material3.Scaffold(
|
|
||||||
topBar = {
|
|
||||||
androidx.compose.material3.TopAppBar(
|
|
||||||
title = {
|
|
||||||
androidx.compose.material3.Text(
|
|
||||||
when {
|
|
||||||
ui.inDetail -> "商品详情"
|
|
||||||
ui.currentTab == Tab.Home -> "KMP Mini Shopping"
|
|
||||||
else -> "购物车"
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
},
|
|
||||||
bottomBar = {
|
|
||||||
if (!ui.inDetail) {
|
|
||||||
androidx.compose.material3.NavigationBar {
|
|
||||||
androidx.compose.material3.NavigationBarItem(
|
|
||||||
selected = ui.currentTab == Tab.Home,
|
|
||||||
onClick = { vm.selectTab(Tab.Home) },
|
|
||||||
icon = { androidx.compose.material3.Text("🏠") },
|
|
||||||
label = { androidx.compose.material3.Text("商品") }
|
|
||||||
)
|
|
||||||
androidx.compose.material3.NavigationBarItem(
|
|
||||||
selected = ui.currentTab == Tab.Cart,
|
|
||||||
onClick = { vm.selectTab(Tab.Cart) },
|
|
||||||
icon = { androidx.compose.material3.Text("🛒") },
|
|
||||||
label = { androidx.compose.material3.Text("购物车") }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
) { padding ->
|
|
||||||
androidx.compose.foundation.layout.Box(
|
|
||||||
androidx.compose.ui.Modifier
|
|
||||||
.padding(padding)
|
|
||||||
.fillMaxSize()
|
|
||||||
) {
|
|
||||||
androidx.compose.material3.Text("内容区")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 本步验收
|
|
||||||
- 顶部标题显示
|
|
||||||
- 底部两个 tab 显示
|
|
||||||
- 中间出现“内容区”
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. 第二步:建三个页面函数(先空实现)
|
|
||||||
|
|
||||||
在 `App.kt` 底部新增:
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
@Composable
|
|
||||||
private fun ProductListScreen() {
|
|
||||||
androidx.compose.material3.Text("商品列表页")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun ProductDetailScreen() {
|
|
||||||
androidx.compose.material3.Text("详情页")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun CartScreen() {
|
|
||||||
androidx.compose.material3.Text("购物车页")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
然后把内容区替换成路由切换:
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
when {
|
|
||||||
ui.inDetail -> ProductDetailScreen()
|
|
||||||
ui.currentTab == Tab.Home -> ProductListScreen()
|
|
||||||
else -> CartScreen()
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 本步验收
|
|
||||||
- 点底栏可切换“商品列表页 / 购物车页”
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. 第三步:把商品列表接上数据(先不用瀑布流)
|
|
||||||
|
|
||||||
先把列表页改成 `LazyColumn` 版本,确保数据逻辑通:
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
@Composable
|
|
||||||
private fun ProductListScreen(
|
|
||||||
products: List<com.example.minishop.model.Product>,
|
|
||||||
onClick: (com.example.minishop.model.Product) -> Unit,
|
|
||||||
onAdd: (com.example.minishop.model.Product) -> Unit
|
|
||||||
) {
|
|
||||||
androidx.compose.foundation.lazy.LazyColumn {
|
|
||||||
items(products, key = { it.id }) { p ->
|
|
||||||
androidx.compose.material3.Card(
|
|
||||||
modifier = androidx.compose.ui.Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(8.dp),
|
|
||||||
onClick = { onClick(p) }
|
|
||||||
) {
|
|
||||||
androidx.compose.foundation.layout.Column(
|
|
||||||
modifier = androidx.compose.ui.Modifier.padding(12.dp)
|
|
||||||
) {
|
|
||||||
androidx.compose.material3.Text(p.title)
|
|
||||||
androidx.compose.material3.Text("¥${p.price}")
|
|
||||||
androidx.compose.material3.Text(p.description)
|
|
||||||
androidx.compose.material3.Button(onClick = { onAdd(p) }) {
|
|
||||||
androidx.compose.material3.Text("加购")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
在 `App()` 里调用:
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
ui.currentTab == Tab.Home -> ProductListScreen(
|
|
||||||
products = vm.filteredProducts,
|
|
||||||
onClick = vm::openDetail,
|
|
||||||
onAdd = { vm.addToCart(it.id) }
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
### 本步验收
|
|
||||||
- 能看到后端商品列表
|
|
||||||
- 点“加购”不崩
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. 第四步:升级为两列瀑布流
|
|
||||||
|
|
||||||
把 `ProductListScreen` 里的 `LazyColumn` 换成:
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
|
|
||||||
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
|
|
||||||
import androidx.compose.foundation.lazy.staggeredgrid.items as staggeredItems
|
|
||||||
|
|
||||||
LazyVerticalStaggeredGrid(
|
|
||||||
columns = StaggeredGridCells.Fixed(2),
|
|
||||||
verticalItemSpacing = 10.dp,
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
|
||||||
modifier = Modifier.fillMaxSize()
|
|
||||||
) {
|
|
||||||
staggeredItems(products, key = { it.id }) { p ->
|
|
||||||
// 卡片内容沿用上一步
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 本步验收
|
|
||||||
- 列表变成两列
|
|
||||||
- 滚动正常
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. 第五步:实现详情页
|
|
||||||
|
|
||||||
改 `ProductDetailScreen` 为:
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
@Composable
|
|
||||||
private fun ProductDetailScreen(
|
|
||||||
product: com.example.minishop.model.Product?,
|
|
||||||
quantity: Int,
|
|
||||||
onAdd: (com.example.minishop.model.Product) -> Unit
|
|
||||||
) {
|
|
||||||
if (product == null) {
|
|
||||||
androidx.compose.material3.Text("商品不存在")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
androidx.compose.foundation.layout.Column(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxSize()
|
|
||||||
.padding(16.dp),
|
|
||||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
|
||||||
) {
|
|
||||||
ProductCover(product.imageUrl)
|
|
||||||
androidx.compose.material3.Text(product.title)
|
|
||||||
androidx.compose.material3.Text("¥${product.price}")
|
|
||||||
androidx.compose.material3.Text(product.description)
|
|
||||||
if (quantity > 0) {
|
|
||||||
androidx.compose.material3.Text("当前已加购:$quantity")
|
|
||||||
}
|
|
||||||
androidx.compose.material3.Button(onClick = { onAdd(product) }) {
|
|
||||||
androidx.compose.material3.Text("加入购物车")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`App()` 里调用:
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
ui.inDetail -> ProductDetailScreen(
|
|
||||||
product = vm.selectedProduct,
|
|
||||||
quantity = vm.selectedProduct?.let { vm.quantityOf(it.id) } ?: 0,
|
|
||||||
onAdd = { vm.addToCart(it.id) }
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
### 本步验收
|
|
||||||
- 点商品进入详情
|
|
||||||
- 详情页可加购
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. 第六步:实现购物车页(先行项目)
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
|
||||||
import androidx.compose.foundation.lazy.items as lazyListItems
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun CartScreen(
|
|
||||||
items: List<com.example.minishop.cart.CartItem>,
|
|
||||||
productMap: Map<String, com.example.minishop.model.Product>,
|
|
||||||
onInc: (String) -> Unit,
|
|
||||||
onDec: (String) -> Unit,
|
|
||||||
onRemove: (String) -> Unit
|
|
||||||
) {
|
|
||||||
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
|
||||||
lazyListItems(items) { item ->
|
|
||||||
val p = productMap[item.productId] ?: return@lazyListItems
|
|
||||||
androidx.compose.material3.Card(Modifier.fillMaxWidth()) {
|
|
||||||
androidx.compose.foundation.layout.Column(Modifier.padding(12.dp)) {
|
|
||||||
androidx.compose.material3.Text(p.title)
|
|
||||||
androidx.compose.material3.Text("数量:${item.quantity}")
|
|
||||||
androidx.compose.foundation.layout.Row {
|
|
||||||
androidx.compose.material3.OutlinedButton(onClick = { onDec(p.id) }) { androidx.compose.material3.Text("-") }
|
|
||||||
androidx.compose.material3.OutlinedButton(onClick = { onInc(p.id) }) { androidx.compose.material3.Text("+") }
|
|
||||||
androidx.compose.material3.OutlinedButton(onClick = { onRemove(p.id) }) { androidx.compose.material3.Text("移除") }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 本步验收
|
|
||||||
- 购物车可增减删
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. 第七步:加“底部固定结算栏”
|
|
||||||
|
|
||||||
把 `CartScreen` 外层改成 `Box`:
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
Box(Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 12.dp)) {
|
|
||||||
LazyColumn(
|
|
||||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
|
||||||
contentPadding = PaddingValues(bottom = 96.dp)
|
|
||||||
) {
|
|
||||||
// 购物车项
|
|
||||||
}
|
|
||||||
|
|
||||||
Card(
|
|
||||||
modifier = Modifier
|
|
||||||
.align(Alignment.BottomCenter)
|
|
||||||
.fillMaxWidth()
|
|
||||||
) {
|
|
||||||
// 总件数、总价、清空、结算
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 本步验收
|
|
||||||
- 结算栏固定在底部
|
|
||||||
- 列表最后一项不会被遮挡
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. 第八步:补图片组件(失败兜底)
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
@Composable
|
|
||||||
private fun ProductCover(url: String) {
|
|
||||||
val coverModifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.height(150.dp)
|
|
||||||
.clip(RoundedCornerShape(12.dp))
|
|
||||||
|
|
||||||
if (url.isNotBlank()) {
|
|
||||||
coil3.compose.SubcomposeAsyncImage(
|
|
||||||
model = url,
|
|
||||||
contentDescription = null,
|
|
||||||
modifier = coverModifier,
|
|
||||||
contentScale = ContentScale.Crop,
|
|
||||||
loading = {
|
|
||||||
androidx.compose.foundation.Image(
|
|
||||||
painter = painterResource(id = R.drawable.course_cover_default),
|
|
||||||
contentDescription = null,
|
|
||||||
modifier = coverModifier,
|
|
||||||
contentScale = ContentScale.Crop
|
|
||||||
)
|
|
||||||
},
|
|
||||||
error = {
|
|
||||||
androidx.compose.foundation.Image(
|
|
||||||
painter = painterResource(id = R.drawable.course_cover_default),
|
|
||||||
contentDescription = null,
|
|
||||||
modifier = coverModifier,
|
|
||||||
contentScale = ContentScale.Crop
|
|
||||||
)
|
|
||||||
},
|
|
||||||
success = { coil3.compose.SubcomposeAsyncImageContent() }
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
androidx.compose.foundation.Image(
|
|
||||||
painter = painterResource(id = R.drawable.course_cover_default),
|
|
||||||
contentDescription = null,
|
|
||||||
modifier = coverModifier,
|
|
||||||
contentScale = ContentScale.Crop
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 本步验收
|
|
||||||
- 有网显示网络图
|
|
||||||
- 慢网/失败显示本地图
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 9. 第九步:把搜索框加上
|
|
||||||
|
|
||||||
在列表页顶部加:
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
OutlinedTextField(
|
|
||||||
value = query,
|
|
||||||
onValueChange = onQueryChange,
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
label = { Text("搜索课程") },
|
|
||||||
singleLine = true
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
ViewModel 内做 `trim()` 过滤。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 10. 最终对照(和当前项目一致)
|
|
||||||
|
|
||||||
最终应达到:
|
|
||||||
- 首页两列瀑布流
|
|
||||||
- 详情页
|
|
||||||
- 购物车增减删清
|
|
||||||
- 底部固定结算栏
|
|
||||||
- 图片兜底
|
|
||||||
- 搜索过滤
|
|
||||||
- 事件全部走 `ShopViewModel`
|
|
||||||
|
|
||||||
如果学员跟到第10步还有问题,直接对照:
|
|
||||||
- `App.kt`
|
|
||||||
- `ShopViewModel.kt`
|
|
||||||
@@ -1,500 +0,0 @@
|
|||||||
# 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<Product?>(null) }
|
|
||||||
var inDetail by remember { mutableStateOf(false) }
|
|
||||||
|
|
||||||
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) }
|
|
||||||
|
|
||||||
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<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(
|
|
||||||
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
|
|
||||||
@@ -1,387 +0,0 @@
|
|||||||
# 第1课|KMP Mini Shopping:共享层 + 首页/详情页(纯讲解版)
|
|
||||||
|
|
||||||
> 本课目标:
|
|
||||||
> 1) 完成 shared 业务层;2) 完成 Android 首页/详情;3) 项目可运行;4) 留课后作业
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. 本课讲解思路
|
|
||||||
|
|
||||||
本课先建立项目分层,再完成最小业务闭环。
|
|
||||||
|
|
||||||
- `shared/commonMain`:业务模型与状态逻辑(可复用)
|
|
||||||
- `composeApp/androidMain`:页面展示与交互
|
|
||||||
|
|
||||||
这样做的目的:页面只负责展示,业务规则集中管理,后续扩展成本低。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. 创建项目与基础设置
|
|
||||||
|
|
||||||
使用 KMP Wizard 创建 Android+iOS 模板(iOS 本课不讲)。
|
|
||||||
|
|
||||||
统一以下配置:
|
|
||||||
|
|
||||||
### 2.1 `settings.gradle.kts`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
rootProject.name = "kmp-mini-shopping"
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2.2 `composeApp/build.gradle.kts`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
android {
|
|
||||||
namespace = "com.example.minishop"
|
|
||||||
defaultConfig {
|
|
||||||
applicationId = "com.example.minishop"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. 编写 shared 业务层(老师现场敲)
|
|
||||||
|
|
||||||
路径:`shared/src/commonMain/kotlin/com/example/minishop/`
|
|
||||||
|
|
||||||
### 3.1 `model/Product.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.model
|
|
||||||
|
|
||||||
data class Product(
|
|
||||||
val id: String,
|
|
||||||
val title: String,
|
|
||||||
val price: Double,
|
|
||||||
val description: String
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3.2 `data/ProductRepository.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.data
|
|
||||||
|
|
||||||
import com.example.minishop.model.Product
|
|
||||||
|
|
||||||
interface ProductRepository {
|
|
||||||
fun getProducts(): List<Product>
|
|
||||||
fun getProductById(id: String): Product?
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3.3 `data/FakeProductRepository.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.data
|
|
||||||
|
|
||||||
import com.example.minishop.model.Product
|
|
||||||
|
|
||||||
class FakeProductRepository : ProductRepository {
|
|
||||||
private val products = listOf(
|
|
||||||
Product("1", "KMP 入门课", 99.0, "跨平台开发基础课程"),
|
|
||||||
Product("2", "Compose 实战课", 149.0, "Compose 多端 UI 实战"),
|
|
||||||
Product("3", "Kotlin 协程训练营", 129.0, "协程与 Flow 进阶"),
|
|
||||||
Product("4", "Clean 架构速成", 199.0, "从0构建可维护架构"),
|
|
||||||
Product("5", "SQLDelight 实战", 119.0, "KMP 本地数据库方案"),
|
|
||||||
Product("6", "Ktor API 实战", 159.0, "跨平台网络层搭建")
|
|
||||||
)
|
|
||||||
|
|
||||||
override fun getProducts(): List<Product> = products
|
|
||||||
override fun getProductById(id: String): Product? = products.find { it.id == id }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3.4 `data/FavoriteStore.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.data
|
|
||||||
|
|
||||||
class FavoriteStore {
|
|
||||||
private val ids = linkedSetOf<String>()
|
|
||||||
|
|
||||||
fun isFavorite(productId: String): Boolean = ids.contains(productId)
|
|
||||||
fun all(): Set<String> = ids.toSet()
|
|
||||||
|
|
||||||
fun toggle(productId: String) {
|
|
||||||
if (!ids.add(productId)) ids.remove(productId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3.5 `cart/CartModels.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.cart
|
|
||||||
|
|
||||||
import com.example.minishop.model.Product
|
|
||||||
|
|
||||||
data class CartItem(
|
|
||||||
val product: Product,
|
|
||||||
val quantity: Int
|
|
||||||
)
|
|
||||||
|
|
||||||
data class CartState(
|
|
||||||
val items: List<CartItem> = emptyList()
|
|
||||||
) {
|
|
||||||
val totalCount: Int get() = items.sumOf { it.quantity }
|
|
||||||
val totalPrice: Double get() = items.sumOf { it.product.price * it.quantity }
|
|
||||||
|
|
||||||
fun quantityOf(productId: String): Int =
|
|
||||||
items.firstOrNull { it.product.id == productId }?.quantity ?: 0
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3.6 `cart/CartStore.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop.cart
|
|
||||||
|
|
||||||
import com.example.minishop.model.Product
|
|
||||||
|
|
||||||
class CartStore {
|
|
||||||
private val mutable = mutableMapOf<String, CartItem>()
|
|
||||||
|
|
||||||
fun state(): CartState = CartState(mutable.values.sortedBy { it.product.id })
|
|
||||||
|
|
||||||
fun add(product: Product) {
|
|
||||||
val exist = mutable[product.id]
|
|
||||||
mutable[product.id] = if (exist == null) CartItem(product, 1) else exist.copy(quantity = exist.quantity + 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun increase(productId: String) {
|
|
||||||
val item = mutable[productId] ?: return
|
|
||||||
mutable[productId] = item.copy(quantity = item.quantity + 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun decrease(productId: String) {
|
|
||||||
val item = mutable[productId] ?: return
|
|
||||||
if (item.quantity <= 1) mutable.remove(productId)
|
|
||||||
else mutable[productId] = item.copy(quantity = item.quantity - 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun remove(productId: String) { mutable.remove(productId) }
|
|
||||||
fun clear() { mutable.clear() }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Android 首页与详情(老师现场敲)
|
|
||||||
|
|
||||||
### 4.1 `MainActivity.kt`
|
|
||||||
|
|
||||||
路径:`composeApp/src/androidMain/kotlin/com/example/minishop/MainActivity.kt`
|
|
||||||
|
|
||||||
```kotlin
|
|
||||||
package com.example.minishop
|
|
||||||
|
|
||||||
import android.os.Bundle
|
|
||||||
import androidx.activity.ComponentActivity
|
|
||||||
import androidx.activity.compose.setContent
|
|
||||||
|
|
||||||
class MainActivity : ComponentActivity() {
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
|
||||||
super.onCreate(savedInstanceState)
|
|
||||||
setContent { App() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4.2 `App.kt`(第1课版本:仅首页+详情)
|
|
||||||
|
|
||||||
路径:`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.ElevatedCard
|
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
|
||||||
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.CartStore
|
|
||||||
import com.example.minishop.data.FakeProductRepository
|
|
||||||
import com.example.minishop.data.FavoriteStore
|
|
||||||
import com.example.minishop.model.Product
|
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
|
||||||
@Composable
|
|
||||||
fun App() {
|
|
||||||
MaterialTheme {
|
|
||||||
val repo = remember { FakeProductRepository() }
|
|
||||||
val cartStore = remember { CartStore() }
|
|
||||||
val favoriteStore = remember { FavoriteStore() }
|
|
||||||
|
|
||||||
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 cartState = remember(tick) { cartStore.state() }
|
|
||||||
|
|
||||||
Scaffold(
|
|
||||||
topBar = {
|
|
||||||
TopAppBar(
|
|
||||||
title = { Text(if (inDetail) "商品详情" else "Mini Shopping") },
|
|
||||||
actions = {
|
|
||||||
if (inDetail) {
|
|
||||||
TextButton(onClick = { inDetail = false }) { Text("返回") }
|
|
||||||
} else {
|
|
||||||
Text("购物车(${cartState.totalCount})", modifier = Modifier.padding(end = 12.dp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
) { padding ->
|
|
||||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
|
||||||
if (inDetail) {
|
|
||||||
ProductDetailScreen(
|
|
||||||
product = selected,
|
|
||||||
isFavorite = selected?.let { favoriteStore.isFavorite(it.id) } == true,
|
|
||||||
onToggleFavorite = {
|
|
||||||
selected?.let {
|
|
||||||
favoriteStore.toggle(it.id)
|
|
||||||
tick++
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onAdd = {
|
|
||||||
cartStore.add(it)
|
|
||||||
tick++
|
|
||||||
}
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
ProductListScreen(
|
|
||||||
products = products,
|
|
||||||
query = query,
|
|
||||||
onQueryChange = { query = it },
|
|
||||||
isFavorite = { favoriteStore.isFavorite(it) },
|
|
||||||
quantityOf = { cartState.quantityOf(it) },
|
|
||||||
onToggleFavorite = { id ->
|
|
||||||
favoriteStore.toggle(id)
|
|
||||||
tick++
|
|
||||||
},
|
|
||||||
onOpen = {
|
|
||||||
selected = it
|
|
||||||
inDetail = true
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun ProductListScreen(
|
|
||||||
products: List<Product>,
|
|
||||||
query: String,
|
|
||||||
onQueryChange: (String) -> Unit,
|
|
||||||
isFavorite: (String) -> Boolean,
|
|
||||||
quantityOf: (String) -> Int,
|
|
||||||
onToggleFavorite: (String) -> Unit,
|
|
||||||
onOpen: (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("输入标题或描述") }
|
|
||||||
)
|
|
||||||
|
|
||||||
LazyColumn(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)) {
|
|
||||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
|
||||||
Text(p.title, style = MaterialTheme.typography.titleMedium)
|
|
||||||
Text("¥${"%.2f".format(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")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun ProductDetailScreen(
|
|
||||||
product: Product?,
|
|
||||||
isFavorite: Boolean,
|
|
||||||
onToggleFavorite: () -> Unit,
|
|
||||||
onAdd: (Product) -> Unit
|
|
||||||
) {
|
|
||||||
if (product == null) return
|
|
||||||
|
|
||||||
Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
|
||||||
Text(product.title, style = MaterialTheme.typography.headlineSmall)
|
|
||||||
Text("价格:¥${"%.2f".format(product.price)}")
|
|
||||||
Text(product.description)
|
|
||||||
|
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
|
||||||
Button(onClick = { onAdd(product) }) { Text("加入购物车") }
|
|
||||||
OutlinedButton(onClick = onToggleFavorite) {
|
|
||||||
Text(if (isFavorite) "取消收藏" else "收藏")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. 本课运行与作业
|
|
||||||
|
|
||||||
### 5.1 运行
|
|
||||||
|
|
||||||
```bash
|
|
||||||
./gradlew :composeApp:assembleDebug
|
|
||||||
```
|
|
||||||
|
|
||||||
### 5.2 本课作业
|
|
||||||
|
|
||||||
1. 将 `ProductListScreen` 中价格颜色改为主题主色。
|
|
||||||
2. 搜索框增加“清空”按钮。
|
|
||||||
3. 在详情页增加“当前购物车件数”显示。
|
|
||||||
|
|
||||||
@@ -1,365 +0,0 @@
|
|||||||
# 第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. 购物车增加“结算按钮(仅弹提示)”。
|
|
||||||
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
# 第6-7节课程大纲|KMP 商城:网络与存储实战
|
|
||||||
|
|
||||||
## 课程定位
|
|
||||||
|
|
||||||
在前序 KMP 基础(共享模型、共享逻辑、Android UI 调用)之上,完成“共享层网络 + 共享层存储 + 业务整合”闭环。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 第6节:KMP 商城——共享层开发(含网络 / 存储)
|
|
||||||
|
|
||||||
### 课堂目标
|
|
||||||
|
|
||||||
- 把商城核心逻辑、网络请求、本地存储全部放在 `shared/commonMain`
|
|
||||||
- Android 仅负责页面展示与事件分发
|
|
||||||
- 输出“可运行、可持久化”的最小商城能力
|
|
||||||
|
|
||||||
### 课堂内容(1-2 小时)
|
|
||||||
|
|
||||||
1. **前置准备(5 分钟)**
|
|
||||||
- 配置 Ktor 与 Multiplatform Settings 依赖
|
|
||||||
- 确认 Android 网络权限
|
|
||||||
|
|
||||||
2. **共享层开发(60-80 分钟)**
|
|
||||||
- 共享数据模型:`Product`、`CartItem`
|
|
||||||
- 网络层:Ktor Client 封装、商品列表接口
|
|
||||||
- 存储层:Settings 持久化购物车 JSON
|
|
||||||
- 平台差异:`expect/actual` 提供平台信息
|
|
||||||
- Android 调用共享层:商品加载、加购、数量展示
|
|
||||||
|
|
||||||
3. **课堂验收(10-15 分钟)**
|
|
||||||
- 可加载商品列表
|
|
||||||
- 可加购
|
|
||||||
- 重启后购物车不丢失
|
|
||||||
|
|
||||||
### 课堂产出
|
|
||||||
|
|
||||||
- 带网络 + 存储的共享层代码
|
|
||||||
- Android 可运行 Demo(列表加载、加购、持久化)
|
|
||||||
|
|
||||||
### 课后作业(2小时)
|
|
||||||
|
|
||||||
在课堂内容完成基础上,完成以下两项扩展作业:
|
|
||||||
- 购物车批量操作(全选删除 / 批量 +1)
|
|
||||||
- 列表加载失败重试按钮与错误态
|
|
||||||
|
|
||||||
提交:运行截图(即可)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 第7节:KMP 商城——功能整合 + 结业实战
|
|
||||||
|
|
||||||
### 课堂目标
|
|
||||||
|
|
||||||
- 完成商城流程整合(列表→详情→购物车→结算)
|
|
||||||
- 复盘网络/存储最佳实践
|
|
||||||
- 形成可演示的结业 Demo
|
|
||||||
|
|
||||||
### 课堂内容(1-2 小时)
|
|
||||||
|
|
||||||
1. **功能完善(60-80 分钟)**
|
|
||||||
- 基于持久化数据计算购物车总价
|
|
||||||
- 结算逻辑(模拟)放在共享层
|
|
||||||
- Android 只负责调用与展示
|
|
||||||
|
|
||||||
3. **技能复盘(10-15 分钟)**
|
|
||||||
- 哪些逻辑应放 `commonMain`
|
|
||||||
- 跨平台网络/存储常见踩坑
|
|
||||||
|
|
||||||
4. **课程验收(10 分钟)**
|
|
||||||
- 全流程演示
|
|
||||||
- 冷启动数据一致
|
|
||||||
|
|
||||||
### 课堂产出
|
|
||||||
|
|
||||||
- 完整可演示 KMP 商城 Demo
|
|
||||||
- 网络 + 存储 + 业务逻辑均在共享层
|
|
||||||
|
|
||||||
### 课后作业(2小时)
|
|
||||||
|
|
||||||
在课堂已完成功能基础上,新增“课程外扩展能力”(至少完成2项):
|
|
||||||
- 新增搜索防抖与空态页优化
|
|
||||||
- 新增结算页(含优惠券/折扣规则,规则放共享层)
|
|
||||||
- 新增本地缓存过期策略(时间戳+刷新)
|
|
||||||
- 新增错误重试机制(网络失败重试与提示)
|
|
||||||
|
|
||||||
提交:运行截图(即可)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 与 SkillMap 对应关系
|
|
||||||
|
|
||||||
| 课程节数 | 对应 SkillMap 节点 | 实战覆盖内容 |
|
|
||||||
|---|---|---|
|
|
||||||
| 第6节 | 4. KMP 核心能力 + 5. 跨平台技术栈 | 共享模型/逻辑 + Ktor 网络 + 跨平台存储 |
|
|
||||||
| 第7节 | 5. 跨平台技术栈 + 6. 集成能力 + 7. 业务落地 | 网络/存储整合 + Android 集成 + 商城落地 |
|
|
||||||
|
|
||||||
+24
-48
@@ -1,72 +1,48 @@
|
|||||||
# 第6节:KMP 商城实战——网络 & 存储(新内容)
|
[图片]
|
||||||
|
第6节:KMP 商城实战——网络与存储
|
||||||
对应 SkillMap:
|
对应 SkillMap:
|
||||||
5. 跨平台技术栈(Ktor / Settings / Serialization)
|
5. 跨平台技术栈(Ktor / Settings / Serialization)
|
||||||
|
本节目标
|
||||||
### 本节目标
|
|
||||||
|
|
||||||
- 在 KMP 共享层完成网络请求与本地存储能力
|
- 在 KMP 共享层完成网络请求与本地存储能力
|
||||||
- 商城最小闭环:商品列表(网络)+ 购物车(存储)
|
- 完成商城最小闭环:商品列表(网络)+ 购物车(存储)
|
||||||
- Android 端只做展示与交互,不承载核心业务逻辑
|
- Android 端只做展示与交互,不承载核心业务逻辑
|
||||||
|
本节内容
|
||||||
### 本节内容(1~2小时)
|
|
||||||
|
|
||||||
1. KMP 中集成 Ktor 网络
|
1. KMP 中集成 Ktor 网络
|
||||||
2. 封装通用网络请求能力
|
2. 封装通用网络请求能力
|
||||||
3. 商品列表接口实战(可先 mock 后真实)
|
3. 商品列表接口实战(可先 Mock 后真实)
|
||||||
4. 集成跨平台存储(Multiplatform Settings)
|
4. 集成跨平台存储(Multiplatform Settings)
|
||||||
5. 购物车数据本地持久化
|
5. 购物车数据本地持久化
|
||||||
6. 数据解析(kotlinx-serialization)
|
6. 数据解析(kotlinx-serialization)
|
||||||
|
课堂实战产出
|
||||||
### 课堂实战产出
|
|
||||||
|
|
||||||
- 共享层实现:商品列表拉取 + 购物车持久化
|
- 共享层实现:商品列表拉取 + 购物车持久化
|
||||||
- Android 页面可运行:商品展示、加购、重启后数据不丢失
|
- Android 页面可运行:商品列表展示、加购、重启后数据不丢失
|
||||||
|
课后作业
|
||||||
### 课后作业(≤2小时)
|
- 完成商品详情页面
|
||||||
|
- 购物车操作(删除条目 / 数量修改+- / 清空)
|
||||||
- 完成商品详情接口
|
- 提交运行录屏
|
||||||
- 存储优化:删除 / 数量修改
|
|
||||||
- 提交运行截图 + 核心代码截图
|
|
||||||
|
|
||||||
────────────────────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
# 第7节:KMP 商城实战——架构封装 + 业务整合(新内容)
|
|
||||||
|
|
||||||
|
---
|
||||||
|
第7节:KMP 商城实战——架构封装与业务整合
|
||||||
对应 SkillMap:
|
对应 SkillMap:
|
||||||
4. KMP 核心能力 + 6. 平台集成能力 + 7. 工程化与业务落地
|
4. KMP 核心能力 + 6. 平台集成能力 + 7. 工程化与业务落地
|
||||||
|
本节目标
|
||||||
### 本节目标
|
|
||||||
|
|
||||||
- 将第6节功能重构为标准可维护架构
|
- 将第6节功能重构为标准可维护架构
|
||||||
- 建立共享层分层规范与职责边界
|
- 建立共享层分层规范与职责边界
|
||||||
- 完成可演示、可复用的商城项目结构
|
- 完成可演示、可复用的商城项目结构
|
||||||
|
本节内容
|
||||||
### 本节内容(1~2小时)
|
|
||||||
|
|
||||||
1. KMP 项目分层设计
|
1. KMP 项目分层设计
|
||||||
- common 层分层:data / domain / repository
|
|
||||||
2. 纯逻辑层规范写法
|
2. 纯逻辑层规范写法
|
||||||
- 业务规则与数据访问解耦
|
|
||||||
3. 通用 Repository 封装
|
3. 通用 Repository 封装
|
||||||
- 提升复用性与可测试性
|
|
||||||
4. KMP 与 Android 架构最佳实践
|
4. KMP 与 Android 架构最佳实践
|
||||||
- ViewModel 调用共享层
|
|
||||||
- UI 层职责边界
|
|
||||||
5. 常见问题与避坑
|
5. 常见问题与避坑
|
||||||
- 内存、生命周期、线程
|
课堂实战产出
|
||||||
- 真实项目接入方式
|
|
||||||
|
|
||||||
### 课堂实战产出
|
|
||||||
|
|
||||||
- 将第6节商城重构为标准架构
|
- 将第6节商城重构为标准架构
|
||||||
- 完成可复用、可维护的 KMP 模块
|
- 完成可复用、可维护的 KMP 模块
|
||||||
- 完整商城流程演示通过
|
- 完整商城流程演示通过
|
||||||
|
结业作业
|
||||||
### 结业作业(≤2小时)
|
结算流程补齐(共享层实现)
|
||||||
|
- 新增结算方法(模拟成功/失败)
|
||||||
独立完成并提交:
|
- 结算成功后清空购物车并给出提示
|
||||||
- 网络(商品列表)
|
- 网络加载失败时显示错误态
|
||||||
- 存储(购物车)
|
- 提供“重试”按钮并可恢复
|
||||||
- 架构分层(Repository)
|
提交运行录屏
|
||||||
- Android 页面展示
|
|
||||||
Binary file not shown.
Reference in new issue
Block a user