diff --git a/docs/KMP_两课时教学讲稿_MiniShopping_底导航增强版.md b/docs/KMP_两课时教学讲稿_MiniShopping_底导航增强版.md new file mode 100644 index 0000000..b06133a --- /dev/null +++ b/docs/KMP_两课时教学讲稿_MiniShopping_底导航增强版.md @@ -0,0 +1,439 @@ +# 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(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, + 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, + 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) + +--- + +如果你同意,我下一步直接把**当前项目代码也改成这个底导航版本**(不是只改课件),这样你打开就能演示。 diff --git a/docs/KMP_两课时教学讲稿_MiniShopping_超详细实操版.md b/docs/KMP_两课时教学讲稿_MiniShopping_超详细实操版.md new file mode 100644 index 0000000..290706e --- /dev/null +++ b/docs/KMP_两课时教学讲稿_MiniShopping_超详细实操版.md @@ -0,0 +1,835 @@ +# 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 下载模板 + +打开: + +下载后解压,重命名为: + +```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 + 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 = 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() + + fun isFavorite(productId: String): Boolean = ids.contains(productId) + + fun all(): Set = 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 = 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() + + 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(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, + 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, + 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) **“助教检查清单版”**(按文件对照逐项验收) + diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..2528183 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,28 @@ +# Mini Shopping 课程文档索引 + +> 以后只看这个文件,就能找到全部课件。 + +## 课件目录 + +1. **两课时超详细实操版** + - 文件:`KMP_两课时教学讲稿_MiniShopping_超详细实操版.md` + - 适用:从 0 到 Android+iOS 全流程,逐文件照敲 + +2. **两课时底导航增强版** + - 文件:`KMP_两课时教学讲稿_MiniShopping_底导航增强版.md` + - 适用:强调底部导航(首页/收藏/购物车)课堂演示 + +## 使用方式(给老师) + +- 每次开课前: + ```bash + git pull origin main + ``` +- 然后打开:`docs/README.md` +- 课堂按需要进入对应 md 文档 + +## 约定(后续都按这个) + +- 所有新课件统一放在 `docs/` +- 文件名保持中文可读性 +- 我每次更新后会直接推送 Gitea,你只需 `git pull`