388 lines
12 KiB
Markdown
388 lines
12 KiB
Markdown
# 第1课|KMP Mini Shopping:共享层 + 首页/详情页(纯讲解版)
|
|
|
|
> 本课目标:
|
|
> 1) 完成 shared 业务层;2) 完成 Android 首页/详情;3) 项目可运行;4) 留课后作业
|
|
|
|
---
|
|
|
|
## 1. 本课讲解思路
|
|
|
|
本课先建立项目分层,再完成最小业务闭环。
|
|
|
|
- `shared/commonMain`:业务模型与状态逻辑(可复用)
|
|
- `composeApp/androidMain`:页面展示与交互
|
|
|
|
这样做的目的:页面只负责展示,业务规则集中管理,后续扩展成本低。
|
|
|
|
---
|
|
|
|
## 2. 创建项目与基础设置
|
|
|
|
使用 KMP Wizard 创建 Android+iOS 模板(iOS 本课不讲)。
|
|
|
|
统一以下配置:
|
|
|
|
### 2.1 `settings.gradle.kts`
|
|
|
|
```kotlin
|
|
rootProject.name = "kmp-mini-shopping"
|
|
```
|
|
|
|
### 2.2 `composeApp/build.gradle.kts`
|
|
|
|
```kotlin
|
|
android {
|
|
namespace = "com.example.minishop"
|
|
defaultConfig {
|
|
applicationId = "com.example.minishop"
|
|
}
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## 3. 编写 shared 业务层(老师现场敲)
|
|
|
|
路径:`shared/src/commonMain/kotlin/com/example/minishop/`
|
|
|
|
### 3.1 `model/Product.kt`
|
|
|
|
```kotlin
|
|
package com.example.minishop.model
|
|
|
|
data class Product(
|
|
val id: String,
|
|
val title: String,
|
|
val price: Double,
|
|
val description: String
|
|
)
|
|
```
|
|
|
|
### 3.2 `data/ProductRepository.kt`
|
|
|
|
```kotlin
|
|
package com.example.minishop.data
|
|
|
|
import com.example.minishop.model.Product
|
|
|
|
interface ProductRepository {
|
|
fun getProducts(): List<Product>
|
|
fun getProductById(id: String): Product?
|
|
}
|
|
```
|
|
|
|
### 3.3 `data/FakeProductRepository.kt`
|
|
|
|
```kotlin
|
|
package com.example.minishop.data
|
|
|
|
import com.example.minishop.model.Product
|
|
|
|
class FakeProductRepository : ProductRepository {
|
|
private val products = listOf(
|
|
Product("1", "KMP 入门课", 99.0, "跨平台开发基础课程"),
|
|
Product("2", "Compose 实战课", 149.0, "Compose 多端 UI 实战"),
|
|
Product("3", "Kotlin 协程训练营", 129.0, "协程与 Flow 进阶"),
|
|
Product("4", "Clean 架构速成", 199.0, "从0构建可维护架构"),
|
|
Product("5", "SQLDelight 实战", 119.0, "KMP 本地数据库方案"),
|
|
Product("6", "Ktor API 实战", 159.0, "跨平台网络层搭建")
|
|
)
|
|
|
|
override fun getProducts(): List<Product> = products
|
|
override fun getProductById(id: String): Product? = products.find { it.id == id }
|
|
}
|
|
```
|
|
|
|
### 3.4 `data/FavoriteStore.kt`
|
|
|
|
```kotlin
|
|
package com.example.minishop.data
|
|
|
|
class FavoriteStore {
|
|
private val ids = linkedSetOf<String>()
|
|
|
|
fun isFavorite(productId: String): Boolean = ids.contains(productId)
|
|
fun all(): Set<String> = ids.toSet()
|
|
|
|
fun toggle(productId: String) {
|
|
if (!ids.add(productId)) ids.remove(productId)
|
|
}
|
|
}
|
|
```
|
|
|
|
### 3.5 `cart/CartModels.kt`
|
|
|
|
```kotlin
|
|
package com.example.minishop.cart
|
|
|
|
import com.example.minishop.model.Product
|
|
|
|
data class CartItem(
|
|
val product: Product,
|
|
val quantity: Int
|
|
)
|
|
|
|
data class CartState(
|
|
val items: List<CartItem> = emptyList()
|
|
) {
|
|
val totalCount: Int get() = items.sumOf { it.quantity }
|
|
val totalPrice: Double get() = items.sumOf { it.product.price * it.quantity }
|
|
|
|
fun quantityOf(productId: String): Int =
|
|
items.firstOrNull { it.product.id == productId }?.quantity ?: 0
|
|
}
|
|
```
|
|
|
|
### 3.6 `cart/CartStore.kt`
|
|
|
|
```kotlin
|
|
package com.example.minishop.cart
|
|
|
|
import com.example.minishop.model.Product
|
|
|
|
class CartStore {
|
|
private val mutable = mutableMapOf<String, CartItem>()
|
|
|
|
fun state(): CartState = CartState(mutable.values.sortedBy { it.product.id })
|
|
|
|
fun add(product: Product) {
|
|
val exist = mutable[product.id]
|
|
mutable[product.id] = if (exist == null) CartItem(product, 1) else exist.copy(quantity = exist.quantity + 1)
|
|
}
|
|
|
|
fun increase(productId: String) {
|
|
val item = mutable[productId] ?: return
|
|
mutable[productId] = item.copy(quantity = item.quantity + 1)
|
|
}
|
|
|
|
fun decrease(productId: String) {
|
|
val item = mutable[productId] ?: return
|
|
if (item.quantity <= 1) mutable.remove(productId)
|
|
else mutable[productId] = item.copy(quantity = item.quantity - 1)
|
|
}
|
|
|
|
fun remove(productId: String) { mutable.remove(productId) }
|
|
fun clear() { mutable.clear() }
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## 4. Android 首页与详情(老师现场敲)
|
|
|
|
### 4.1 `MainActivity.kt`
|
|
|
|
路径:`composeApp/src/androidMain/kotlin/com/example/minishop/MainActivity.kt`
|
|
|
|
```kotlin
|
|
package com.example.minishop
|
|
|
|
import android.os.Bundle
|
|
import androidx.activity.ComponentActivity
|
|
import androidx.activity.compose.setContent
|
|
|
|
class MainActivity : ComponentActivity() {
|
|
override fun onCreate(savedInstanceState: Bundle?) {
|
|
super.onCreate(savedInstanceState)
|
|
setContent { App() }
|
|
}
|
|
}
|
|
```
|
|
|
|
### 4.2 `App.kt`(第1课版本:仅首页+详情)
|
|
|
|
路径:`composeApp/src/androidMain/kotlin/com/example/minishop/App.kt`
|
|
|
|
```kotlin
|
|
package com.example.minishop
|
|
|
|
import androidx.compose.foundation.layout.Arrangement
|
|
import androidx.compose.foundation.layout.Box
|
|
import androidx.compose.foundation.layout.Column
|
|
import androidx.compose.foundation.layout.Row
|
|
import androidx.compose.foundation.layout.fillMaxSize
|
|
import androidx.compose.foundation.layout.fillMaxWidth
|
|
import androidx.compose.foundation.layout.padding
|
|
import androidx.compose.foundation.lazy.LazyColumn
|
|
import androidx.compose.foundation.lazy.items
|
|
import androidx.compose.material3.Button
|
|
import androidx.compose.material3.ElevatedCard
|
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
|
import androidx.compose.material3.MaterialTheme
|
|
import androidx.compose.material3.OutlinedButton
|
|
import androidx.compose.material3.OutlinedTextField
|
|
import androidx.compose.material3.Scaffold
|
|
import androidx.compose.material3.Text
|
|
import androidx.compose.material3.TextButton
|
|
import androidx.compose.material3.TopAppBar
|
|
import androidx.compose.runtime.Composable
|
|
import androidx.compose.runtime.getValue
|
|
import androidx.compose.runtime.mutableStateOf
|
|
import androidx.compose.runtime.remember
|
|
import androidx.compose.runtime.setValue
|
|
import androidx.compose.ui.Modifier
|
|
import androidx.compose.ui.unit.dp
|
|
import com.example.minishop.cart.CartStore
|
|
import com.example.minishop.data.FakeProductRepository
|
|
import com.example.minishop.data.FavoriteStore
|
|
import com.example.minishop.model.Product
|
|
|
|
@OptIn(ExperimentalMaterial3Api::class)
|
|
@Composable
|
|
fun App() {
|
|
MaterialTheme {
|
|
val repo = remember { FakeProductRepository() }
|
|
val cartStore = remember { CartStore() }
|
|
val favoriteStore = remember { FavoriteStore() }
|
|
|
|
var selected by remember { mutableStateOf<Product?>(null) }
|
|
var inDetail by remember { mutableStateOf(false) }
|
|
var tick by remember { mutableStateOf(0) }
|
|
var query by remember { mutableStateOf("") }
|
|
|
|
val allProducts = remember { repo.getProducts() }
|
|
val products = remember(query, tick) {
|
|
allProducts.filter {
|
|
it.title.contains(query, ignoreCase = true) ||
|
|
it.description.contains(query, ignoreCase = true)
|
|
}
|
|
}
|
|
|
|
val cartState = remember(tick) { cartStore.state() }
|
|
|
|
Scaffold(
|
|
topBar = {
|
|
TopAppBar(
|
|
title = { Text(if (inDetail) "商品详情" else "Mini Shopping") },
|
|
actions = {
|
|
if (inDetail) {
|
|
TextButton(onClick = { inDetail = false }) { Text("返回") }
|
|
} else {
|
|
Text("购物车(${cartState.totalCount})", modifier = Modifier.padding(end = 12.dp))
|
|
}
|
|
}
|
|
)
|
|
}
|
|
) { padding ->
|
|
Box(Modifier.padding(padding).fillMaxSize()) {
|
|
if (inDetail) {
|
|
ProductDetailScreen(
|
|
product = selected,
|
|
isFavorite = selected?.let { favoriteStore.isFavorite(it.id) } == true,
|
|
onToggleFavorite = {
|
|
selected?.let {
|
|
favoriteStore.toggle(it.id)
|
|
tick++
|
|
}
|
|
},
|
|
onAdd = {
|
|
cartStore.add(it)
|
|
tick++
|
|
}
|
|
)
|
|
} else {
|
|
ProductListScreen(
|
|
products = products,
|
|
query = query,
|
|
onQueryChange = { query = it },
|
|
isFavorite = { favoriteStore.isFavorite(it) },
|
|
quantityOf = { cartState.quantityOf(it) },
|
|
onToggleFavorite = { id ->
|
|
favoriteStore.toggle(id)
|
|
tick++
|
|
},
|
|
onOpen = {
|
|
selected = it
|
|
inDetail = true
|
|
}
|
|
)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
@Composable
|
|
private fun ProductListScreen(
|
|
products: List<Product>,
|
|
query: String,
|
|
onQueryChange: (String) -> Unit,
|
|
isFavorite: (String) -> Boolean,
|
|
quantityOf: (String) -> Int,
|
|
onToggleFavorite: (String) -> Unit,
|
|
onOpen: (Product) -> Unit
|
|
) {
|
|
Column(Modifier.fillMaxSize().padding(12.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
|
OutlinedTextField(
|
|
modifier = Modifier.fillMaxWidth(),
|
|
value = query,
|
|
onValueChange = onQueryChange,
|
|
singleLine = true,
|
|
label = { Text("搜索课程") },
|
|
placeholder = { Text("输入标题或描述") }
|
|
)
|
|
|
|
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
|
items(products) { p ->
|
|
ElevatedCard(onClick = { onOpen(p) }, modifier = Modifier.fillMaxWidth()) {
|
|
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
|
Text(p.title, style = MaterialTheme.typography.titleMedium)
|
|
Text("¥${"%.2f".format(p.price)}")
|
|
}
|
|
Text(p.description, style = MaterialTheme.typography.bodySmall)
|
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
|
OutlinedButton(onClick = { onToggleFavorite(p.id) }) {
|
|
Text(if (isFavorite(p.id)) "已收藏" else "收藏")
|
|
}
|
|
val q = quantityOf(p.id)
|
|
if (q > 0) Text("已加购 x$q")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
@Composable
|
|
private fun ProductDetailScreen(
|
|
product: Product?,
|
|
isFavorite: Boolean,
|
|
onToggleFavorite: () -> Unit,
|
|
onAdd: (Product) -> Unit
|
|
) {
|
|
if (product == null) return
|
|
|
|
Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
|
Text(product.title, style = MaterialTheme.typography.headlineSmall)
|
|
Text("价格:¥${"%.2f".format(product.price)}")
|
|
Text(product.description)
|
|
|
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
|
Button(onClick = { onAdd(product) }) { Text("加入购物车") }
|
|
OutlinedButton(onClick = onToggleFavorite) {
|
|
Text(if (isFavorite) "取消收藏" else "收藏")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## 5. 本课运行与作业
|
|
|
|
### 5.1 运行
|
|
|
|
```bash
|
|
./gradlew :composeApp:assembleDebug
|
|
```
|
|
|
|
### 5.2 本课作业
|
|
|
|
1. 将 `ProductListScreen` 中价格颜色改为主题主色。
|
|
2. 搜索框增加“清空”按钮。
|
|
3. 在详情页增加“当前购物车件数”显示。
|
|
|