docs: add lesson1/lesson2 android-only teaching notes with explanation
This commit is contained in:
1 parent
08324cc60a
commit
2316b2b463
3 files changed
+860
-26
No files matched your search
+11
-26
@@ -1,32 +1,17 @@
|
|||||||
# Mini Shopping 课程文档索引
|
# Mini Shopping 文档索引(课堂使用)
|
||||||
|
|
||||||
> 以后只看这个文件,就能找到全部课件。
|
## 当前推荐(Android 两课时)
|
||||||
|
|
||||||
## 课件目录
|
1. `第1课_KMP_MiniShopping_共享层与首页详情.md`
|
||||||
|
- 内容:共享层建模、首页与详情页、第一课验收
|
||||||
|
|
||||||
0. **两课时群发版(逐步实操)**
|
2. `第2课_KMP_MiniShopping_底导航收藏购物车.md`
|
||||||
- 文件:`KMP_两课时教学讲义_群发版_逐步实操.md`
|
- 内容:底导航、收藏页、购物车页、第二课验收
|
||||||
- 适用:直接发学习群,去除口语化,按步骤执行
|
|
||||||
|
|
||||||
1. **两课时超详细实操版**
|
## 归档文档(历史版本)
|
||||||
- 文件:`KMP_两课时教学讲稿_MiniShopping_超详细实操版.md`
|
|
||||||
- 适用:从 0 到 Android+iOS 全流程,逐文件照敲
|
|
||||||
|
|
||||||
2. **两课时底导航增强版**
|
- `KMP_两课时教学讲稿_MiniShopping_超详细实操版.md`
|
||||||
- 文件:`KMP_两课时教学讲稿_MiniShopping_底导航增强版.md`
|
- `KMP_两课时教学讲稿_MiniShopping_底导航增强版.md`
|
||||||
- 适用:强调底部导航(首页/收藏/购物车)课堂演示
|
- `KMP_两课时教学讲义_群发版_逐步实操.md`
|
||||||
|
|
||||||
## 使用方式(给老师)
|
> 说明:当前课堂请优先使用“第1课/第2课”两份文档。
|
||||||
|
|
||||||
- 每次开课前:
|
|
||||||
```bash
|
|
||||||
git pull origin main
|
|
||||||
```
|
|
||||||
- 然后打开:`docs/README.md`
|
|
||||||
- 课堂按需要进入对应 md 文档
|
|
||||||
|
|
||||||
## 约定(后续都按这个)
|
|
||||||
|
|
||||||
- 所有新课件统一放在 `docs/`
|
|
||||||
- 文件名保持中文可读性
|
|
||||||
- 我每次更新后会直接推送 Gitea,你只需 `git pull`
|
|
||||||
@@ -0,0 +1,448 @@
|
|||||||
|
# 第1课|KMP Mini Shopping:共享层建模 + 首页/详情页
|
||||||
|
|
||||||
|
> 课时目标(90~120分钟)
|
||||||
|
>
|
||||||
|
> 1. 理解 KMP 的分层:`shared` 放业务,`composeApp` 放 Android UI
|
||||||
|
> 2. 完成共享业务层(商品、收藏、购物车基础能力)
|
||||||
|
> 3. 完成 Android 首页(搜索+列表)与详情页(收藏+加购)
|
||||||
|
> 4. Android 端可成功运行
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 一、先讲清楚“为什么这样分层”
|
||||||
|
|
||||||
|
### 1.1 板书(先讲2分钟)
|
||||||
|
|
||||||
|
- `shared/commonMain`:业务规则(数据模型、仓库、购物车逻辑)
|
||||||
|
- `composeApp/androidMain`:页面展示(Compose)
|
||||||
|
|
||||||
|
### 1.2 讲解要点(老师可照读)
|
||||||
|
|
||||||
|
- 今天先不追求“炫 UI”,重点是“共享业务层 + 可运行流程”。
|
||||||
|
- 业务代码不写在页面里,后续功能扩展(收藏、购物车、结算)会更稳。
|
||||||
|
- 第1课结束标准:**首页、详情、收藏、加购打通**。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、创建项目与基础校验
|
||||||
|
|
||||||
|
### Step 2.1 创建模板项目
|
||||||
|
|
||||||
|
使用 KMP Wizard:
|
||||||
|
|
||||||
|
- Android: 开启
|
||||||
|
- iOS: 开启(本课不讲iOS)
|
||||||
|
- iOS UI: SwiftUI
|
||||||
|
- Include tests: 开启
|
||||||
|
|
||||||
|
重命名目录为:`kmp-mini-shopping`
|
||||||
|
|
||||||
|
### Step 2.2 校验项目名与包名
|
||||||
|
|
||||||
|
`settings.gradle.kts`:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
rootProject.name = "kmp-mini-shopping"
|
||||||
|
```
|
||||||
|
|
||||||
|
`composeApp/build.gradle.kts`:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
android {
|
||||||
|
namespace = "com.example.minishop"
|
||||||
|
defaultConfig {
|
||||||
|
applicationId = "com.example.minishop"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 2.3 课堂提问(互动)
|
||||||
|
|
||||||
|
- 问:为什么不把 `Product` 直接写在 `App.kt` 里?
|
||||||
|
- 目标回答:因为 `Product` 是业务数据模型,应该放在共享层,避免 UI 耦合。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、先完成 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
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
**讲解**:
|
||||||
|
- `id` 是业务唯一标识,不用标题当主键。
|
||||||
|
- `price` 用 `Double`,本课先够用。
|
||||||
|
|
||||||
|
### 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?
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**讲解**:
|
||||||
|
- 先定义“能力接口”,再做实现。
|
||||||
|
- 后续替换网络/数据库实现时,UI 层不用大改。
|
||||||
|
|
||||||
|
### 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 }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**讲解**:
|
||||||
|
- `Fake` 的作用是先跑通流程,不被网络问题卡住。
|
||||||
|
- 第2课可布置作业:替换为真实 API。
|
||||||
|
|
||||||
|
### 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**讲解**:
|
||||||
|
- `toggle` 比 `add/remove` 两套按钮更适合课堂演示。
|
||||||
|
- `toSet()` 返回副本,避免外部误改内部状态。
|
||||||
|
|
||||||
|
### 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
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**讲解**:
|
||||||
|
- `CartState` 提供“派生数据”(总件数/总价),页面不重复写计算。
|
||||||
|
|
||||||
|
### 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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**讲解**:
|
||||||
|
- `decrease` 到 0 直接删除,是购物车常见规则。
|
||||||
|
- `state()` 统一出口,UI 只读状态,不直接改 map。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、Android 页面:先“首页+详情”打通
|
||||||
|
|
||||||
|
### Step 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() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 4.2 `App.kt`(本课使用“首页+详情版本”)
|
||||||
|
|
||||||
|
路径:`composeApp/src/androidMain/kotlin/com/example/minishop/App.kt`
|
||||||
|
|
||||||
|
> 说明:第1课先不加底导航,第2课再扩展为底导航版本。
|
||||||
|
|
||||||
|
```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 "收藏")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 五、本课收尾验收
|
||||||
|
|
||||||
|
### Step 5.1 构建
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./gradlew :composeApp:assembleDebug
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 5.2 现场验收点
|
||||||
|
|
||||||
|
- 能启动应用
|
||||||
|
- 首页可搜索
|
||||||
|
- 可进入详情
|
||||||
|
- 详情可收藏
|
||||||
|
- 详情可加入购物车
|
||||||
|
- 顶部购物车数量变化
|
||||||
|
|
||||||
|
### Step 5.3 课后作业
|
||||||
|
|
||||||
|
- 把“购物车页面”补出来(第2课会讲标准实现)
|
||||||
|
|
||||||
@@ -0,0 +1,401 @@
|
|||||||
|
# 第2课|KMP Mini Shopping:底导航 + 收藏页 + 购物车页
|
||||||
|
|
||||||
|
> 课时目标(90~120分钟)
|
||||||
|
>
|
||||||
|
> 1. 在第1课基础上升级为底导航结构(首页/收藏/购物车)
|
||||||
|
> 2. 完成收藏页与购物车页完整闭环
|
||||||
|
> 3. 完成课堂验收与常见问题排查
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 一、复习(5分钟)
|
||||||
|
|
||||||
|
### 1.1 复习问题
|
||||||
|
|
||||||
|
- 共享层放了哪些文件?
|
||||||
|
- 为什么 `CartStore` 不放在 `App.kt` 内部类?
|
||||||
|
|
||||||
|
### 1.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.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.1 底导航为什么放 `Scaffold.bottomBar`
|
||||||
|
|
||||||
|
- 页面骨架统一在 `Scaffold`
|
||||||
|
- 业务切换只改 `currentTab`
|
||||||
|
- 详情页通过 `inDetail` 临时覆盖主流程
|
||||||
|
|
||||||
|
### 3.2 状态管理讲解顺序
|
||||||
|
|
||||||
|
1. `repo/cartStore/favoriteStore`(业务对象)
|
||||||
|
2. `currentTab/selected/inDetail`(页面状态)
|
||||||
|
3. `tick`(刷新触发)
|
||||||
|
4. `remember(tick)` 推导视图状态
|
||||||
|
|
||||||
|
### 3.3 课堂提问
|
||||||
|
|
||||||
|
- 问:为什么收藏数量显示在底导航标签里?
|
||||||
|
- 目标回答:这是“状态驱动 UI”,而不是手动 setText。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、本课验收(必须逐项)
|
||||||
|
|
||||||
|
- 首页:搜索、收藏按钮可用
|
||||||
|
- 收藏页:只显示已收藏商品
|
||||||
|
- 购物车页:加减、移除、清空可用
|
||||||
|
- 详情页:加购/收藏可联动
|
||||||
|
- 底导航数字:收藏数量、购物车数量实时变化
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 五、常见错误与修复
|
||||||
|
|
||||||
|
1. 错误:`TopAppBar experimental`
|
||||||
|
- 修复:
|
||||||
|
- `import androidx.compose.material3.ExperimentalMaterial3Api`
|
||||||
|
- `@OptIn(ExperimentalMaterial3Api::class)`
|
||||||
|
|
||||||
|
2. 错误:`Unresolved reference: CartStore`
|
||||||
|
- 修复:确认 `shared/commonMain` 下 `cart/CartStore.kt` 已创建且 package 正确。
|
||||||
|
|
||||||
|
3. 错误:页面不刷新
|
||||||
|
- 修复:检查修改数据后是否 `tick++`。
|
||||||
|
|
||||||
Reference in new issue
Block a user