836 lines
25 KiB
Markdown
836 lines
25 KiB
Markdown
# 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) **“助教检查清单版”**(按文件对照逐项验收)
|
||
|