# 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 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 = 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() fun isFavorite(productId: String): Boolean = ids.contains(productId) fun all(): Set = 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 = 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() 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(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, 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) ``` --- ## 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 运行截图