Compare commits
67
Commits
df1b90c9b2
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
076d0efb27 | ||
|
|
a0ae9eff02 | ||
|
|
b9933f8822 | ||
|
|
0e5eff673b | ||
|
|
a773ac7867 | ||
|
|
9dfe6747dd | ||
|
|
e42597b8b7 | ||
|
|
fc8ea48ea1 | ||
|
|
605b78eb50 | ||
|
|
5147bb7bcc | ||
|
|
4f32be7077 | ||
|
|
a5120b3e8a | ||
|
|
adb722f728 | ||
|
|
2931909742 | ||
|
|
54487eb829 | ||
|
|
e6f05b1b64 | ||
|
|
5d3ea97f9f | ||
|
|
de2c488b8b | ||
|
|
5c32d6bdbe | ||
|
|
837caa3058 | ||
|
|
ce062202de | ||
|
|
d9f2f31565 | ||
|
|
89ce9eeb2f | ||
|
|
a12d40f8bb | ||
|
|
1b002d29c7 | ||
|
|
a29d64eb6f | ||
|
|
b98af4ed17 | ||
|
|
ec1bcfa47e | ||
|
|
f2b35a2a3e | ||
|
|
7e649cc26c | ||
|
|
fb828b8796 | ||
|
|
2ac859f46b | ||
|
|
7e5251a809 | ||
|
|
a68d4193bf | ||
|
|
c9707129da | ||
|
|
24945ee3fe | ||
|
|
dc2e32c437 | ||
|
|
a3d4bc9429 | ||
|
|
c089f2179e | ||
|
|
b9e621c9e0 | ||
|
|
5406a7de02 | ||
|
|
0469a45f51 | ||
|
|
3c211d731a | ||
|
|
348f34d610 | ||
|
|
e9119ac7b5 | ||
|
|
23dce047b4 | ||
|
|
f0184b94a3 | ||
|
|
2b51111a04 | ||
|
|
4e10335748 | ||
|
|
c08d9e0189 | ||
|
|
04be5d06f0 | ||
|
|
5196d9da10 | ||
|
|
5e2eb56658 | ||
|
|
575c26eaf5 | ||
|
|
035d396eaf | ||
|
|
823080245d | ||
|
|
7334f326a3 | ||
|
|
f6005e4772 | ||
|
|
02380e8221 | ||
|
|
7c4543cc55 | ||
|
|
e59e64ec61 | ||
|
|
35fbc85fd5 | ||
|
|
1f9159c28e | ||
|
|
2316b2b463 | ||
|
|
08324cc60a | ||
|
|
3fa1580585 | ||
|
|
349d9074c9 |
No files matched your search
@@ -30,3 +30,7 @@ And the following Android-specific dependencies:
|
||||
- [Jetpack Compose](https://developer.android.com/jetpack/compose)
|
||||
- [Navigation component](https://developer.android.com/jetpack/compose/navigation)
|
||||
- [Coil](https://github.com/coil-kt/coil) for image loading
|
||||
|
||||
## Local course notes
|
||||
|
||||
- Koin 最小注入演示:`docs/第7节补充_Koin最小注入演示.md`
|
||||
@@ -0,0 +1,31 @@
|
||||
# kmp-mini-shopping backend
|
||||
|
||||
一个超轻量 Ktor 后端,用于提供商品列表接口。
|
||||
|
||||
## 运行
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
./gradlew run
|
||||
```
|
||||
|
||||
默认监听:`http://localhost:8080`
|
||||
|
||||
## 接口
|
||||
|
||||
- `GET /` 服务状态
|
||||
- `GET /api/health` 健康检查
|
||||
- `GET /api/products` 商品列表(推荐)
|
||||
- `GET /products` 商品列表(兼容)
|
||||
|
||||
## 返回字段
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "1",
|
||||
"title": "KMP 入门课",
|
||||
"price": 99.0,
|
||||
"description": "跨平台开发基础课程",
|
||||
"imageUrl": "https://picsum.photos/seed/kmp1/600/360"
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,28 @@
|
||||
plugins {
|
||||
kotlin("jvm") version "2.2.20"
|
||||
application
|
||||
kotlin("plugin.serialization") version "2.2.20"
|
||||
}
|
||||
|
||||
group = "com.example.minishop"
|
||||
version = "1.0.0"
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("io.ktor:ktor-server-core-jvm:2.3.12")
|
||||
implementation("io.ktor:ktor-server-netty-jvm:2.3.12")
|
||||
implementation("io.ktor:ktor-server-content-negotiation-jvm:2.3.12")
|
||||
implementation("io.ktor:ktor-serialization-kotlinx-json-jvm:2.3.12")
|
||||
implementation("ch.qos.logback:logback-classic:1.5.6")
|
||||
}
|
||||
|
||||
application {
|
||||
mainClass.set("com.example.minishop.backend.MainKt")
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvmToolchain(17)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
rootProject.name = "kmp-mini-shopping-backend"
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.example.minishop.backend
|
||||
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.server.application.Application
|
||||
import io.ktor.server.application.call
|
||||
import io.ktor.server.engine.embeddedServer
|
||||
import io.ktor.server.netty.Netty
|
||||
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.routing.get
|
||||
import io.ktor.server.routing.route
|
||||
import io.ktor.server.routing.routing
|
||||
import io.ktor.serialization.kotlinx.json.json
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class Product(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val price: Double,
|
||||
val description: String,
|
||||
val imageUrl: String = ""
|
||||
)
|
||||
|
||||
fun main() {
|
||||
embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
|
||||
module()
|
||||
}.start(wait = true)
|
||||
}
|
||||
|
||||
fun Application.module() {
|
||||
install(ContentNegotiation) { json() }
|
||||
|
||||
routing {
|
||||
get("/") {
|
||||
call.respond(mapOf("service" to "kmp-mini-shopping-backend", "status" to "ok"))
|
||||
}
|
||||
|
||||
route("/api") {
|
||||
get("/health") {
|
||||
call.respond(HttpStatusCode.OK, mapOf("ok" to true))
|
||||
}
|
||||
|
||||
get("/products") {
|
||||
call.respond(products())
|
||||
}
|
||||
}
|
||||
|
||||
get("/products") {
|
||||
call.respond(products())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun products(): List<Product> = listOf(
|
||||
Product("1", "KMP 入门课", 99.0, "跨平台开发基础课程", "https://picsum.photos/seed/kmp1/600/360"),
|
||||
Product("2", "Compose 实战课", 149.0, "Compose 多端 UI 实战", "https://picsum.photos/seed/kmp2/600/360"),
|
||||
Product("3", "Kotlin 协程训练营", 129.0, "协程与 Flow 进阶", "https://picsum.photos/seed/kmp3/600/360"),
|
||||
Product("4", "Clean 架构速成", 199.0, "从0构建可维护架构", "https://picsum.photos/seed/kmp4/600/360"),
|
||||
Product("5", "SQLDelight 实战", 119.0, "KMP 本地数据库方案", "https://picsum.photos/seed/kmp5/600/360"),
|
||||
Product("6", "Ktor API 实战", 159.0, "跨平台网络层搭建", "https://picsum.photos/seed/kmp6/600/360")
|
||||
)
|
||||
@@ -7,6 +7,7 @@
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:usesCleartextTraffic="true"
|
||||
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
|
||||
@@ -1,165 +1,173 @@
|
||||
package com.example.minishop
|
||||
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.items as lazyListItems
|
||||
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
|
||||
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
|
||||
import androidx.compose.foundation.lazy.staggeredgrid.items as staggeredItems
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
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.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Surface
|
||||
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.runtime.rememberCoroutineScope
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
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 coil3.compose.SubcomposeAsyncImage
|
||||
import coil3.compose.SubcomposeAsyncImageContent
|
||||
import com.example.minishop.cart.CartItem
|
||||
import com.example.minishop.model.Product
|
||||
import com.example.minishop.order.ShopOrder
|
||||
import kotlinx.coroutines.launch
|
||||
import org.koin.androidx.compose.koinViewModel
|
||||
|
||||
private enum class Tab { Home, Favorites, Cart }
|
||||
enum class Tab { Home, Cart, Orders }
|
||||
|
||||
@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() }
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
val scope = rememberCoroutineScope()
|
||||
val vm: ShopViewModel = koinViewModel()
|
||||
val ui = vm.uiState
|
||||
|
||||
Scaffold(
|
||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = {
|
||||
Text(
|
||||
when {
|
||||
inDetail -> "商品详情"
|
||||
currentTab == Tab.Home -> "Mini Shopping"
|
||||
currentTab == Tab.Favorites -> "收藏夹"
|
||||
else -> "购物车"
|
||||
ui.inDetail -> "商品详情"
|
||||
ui.currentTab == Tab.Home -> "KMP Mini Shopping"
|
||||
ui.currentTab == Tab.Cart -> "购物车"
|
||||
else -> "订单列表"
|
||||
}
|
||||
)
|
||||
},
|
||||
actions = {
|
||||
if (inDetail) {
|
||||
TextButton(onClick = { inDetail = false }) { Text("返回") }
|
||||
if (ui.inDetail) {
|
||||
TextButton(onClick = { vm.closeDetail() }) { Text("返回") }
|
||||
} else {
|
||||
Text(
|
||||
text = "共 ${ui.totalCount} 件",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
modifier = Modifier.padding(end = 12.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
if (!inDetail) {
|
||||
if (!ui.inDetail) {
|
||||
NavigationBar {
|
||||
NavigationBarItem(
|
||||
selected = currentTab == Tab.Home,
|
||||
onClick = { currentTab = Tab.Home },
|
||||
selected = ui.currentTab == Tab.Home,
|
||||
onClick = { vm.selectTab(Tab.Home) },
|
||||
icon = { Text("🏠") },
|
||||
label = { 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 },
|
||||
selected = ui.currentTab == Tab.Cart,
|
||||
onClick = { vm.selectTab(Tab.Cart) },
|
||||
icon = { Text("🛒") },
|
||||
label = { Text("购物车(${cartState.totalCount})") }
|
||||
label = { Text("购物车(${ui.totalCount})") }
|
||||
)
|
||||
NavigationBarItem(
|
||||
selected = ui.currentTab == Tab.Orders,
|
||||
onClick = { vm.selectTab(Tab.Orders) },
|
||||
icon = { Text("📦") },
|
||||
label = { Text("订单") }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
Box(
|
||||
Modifier
|
||||
.padding(padding)
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.surface)
|
||||
) {
|
||||
when {
|
||||
inDetail -> ProductDetailScreen(
|
||||
product = selected,
|
||||
isFavorite = selected?.let { favoriteStore.isFavorite(it.id) } == true,
|
||||
onBack = { inDetail = false },
|
||||
onToggleFavorite = {
|
||||
selected?.let {
|
||||
favoriteStore.toggle(it.id)
|
||||
tick++
|
||||
ui.inDetail -> ProductDetailScreen(
|
||||
product = vm.selectedProduct,
|
||||
quantity = vm.selectedProduct?.let { vm.quantityOf(it.id) } ?: 0,
|
||||
onAdd = {
|
||||
val msg = vm.addToCart(it)
|
||||
scope.launch {
|
||||
snackbarHostState.showSnackbar(msg)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
ui.currentTab == Tab.Home -> ProductListScreen(
|
||||
state = ui.productListState,
|
||||
products = vm.filteredProducts,
|
||||
totalProducts = ui.products.size,
|
||||
query = ui.query,
|
||||
quantityOf = vm::quantityOf,
|
||||
onQueryChange = vm::onQueryChange,
|
||||
onRetry = { vm.dispatch(ProductListIntent.Retry) },
|
||||
onAdd = {
|
||||
val msg = vm.addToCart(it)
|
||||
scope.launch {
|
||||
snackbarHostState.showSnackbar(msg)
|
||||
}
|
||||
},
|
||||
onAdd = {
|
||||
cartStore.add(it)
|
||||
tick++
|
||||
onClick = vm::openDetail
|
||||
)
|
||||
|
||||
ui.currentTab == Tab.Cart -> CartScreen(
|
||||
items = ui.cartItems,
|
||||
totalPrice = ui.totalPrice,
|
||||
onInc = vm::increase,
|
||||
onDec = vm::decrease,
|
||||
onRemove = vm::remove,
|
||||
onClear = vm::clear,
|
||||
onCheckout = {
|
||||
val msg = vm.checkout()
|
||||
scope.launch {
|
||||
snackbarHostState.showSnackbar(msg)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
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++ }
|
||||
)
|
||||
else -> OrderScreen(ui.orders)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -168,15 +176,22 @@ fun App() {
|
||||
|
||||
@Composable
|
||||
private fun ProductListScreen(
|
||||
state: ProductListState,
|
||||
products: List<Product>,
|
||||
totalProducts: Int,
|
||||
query: String,
|
||||
onQueryChange: (String) -> Unit,
|
||||
isFavorite: (String) -> Boolean,
|
||||
quantityOf: (String) -> Int,
|
||||
onToggleFavorite: (String) -> Unit,
|
||||
onQueryChange: (String) -> Unit,
|
||||
onRetry: () -> Unit,
|
||||
onAdd: (Product) -> Unit,
|
||||
onClick: (Product) -> Unit
|
||||
) {
|
||||
Column(Modifier.fillMaxSize().padding(12.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp)
|
||||
) {
|
||||
OutlinedTextField(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
value = query,
|
||||
@@ -186,25 +201,61 @@ private fun ProductListScreen(
|
||||
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)
|
||||
Text(
|
||||
text = "共 $totalProducts 条 · 当前显示 ${products.size} 条",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(onClick = { onToggleFavorite(p.id) }) {
|
||||
Text(if (isFavorite(p.id)) "已收藏" else "收藏")
|
||||
when (state) {
|
||||
ProductListState.Loading -> EmptyState("⏳ 加载中...")
|
||||
|
||||
is ProductListState.Error -> {
|
||||
Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer)) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("加载失败:${state.message}", color = MaterialTheme.colorScheme.onErrorContainer)
|
||||
Button(onClick = onRetry) { Text("重试") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ProductListState.Empty -> EmptyState("没有匹配的商品")
|
||||
|
||||
is ProductListState.Success -> {
|
||||
LazyVerticalStaggeredGrid(
|
||||
columns = StaggeredGridCells.Fixed(2),
|
||||
verticalItemSpacing = 10.dp,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
modifier = Modifier.fillMaxSize()
|
||||
) {
|
||||
staggeredItems(products, key = { it.id }) { p ->
|
||||
ElevatedCard(onClick = { onClick(p) }, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(10.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
ProductCover(p.imageUrl)
|
||||
Text(
|
||||
p.title,
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = FontWeight.SemiBold
|
||||
)
|
||||
PriceTag(p.price)
|
||||
Text(
|
||||
p.description,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
maxLines = 3
|
||||
)
|
||||
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Button(onClick = { onAdd(p) }) { Text("加购") }
|
||||
Spacer(Modifier.width(8.dp))
|
||||
val q = quantityOf(p.id)
|
||||
if (q > 0) {
|
||||
Text(
|
||||
text = "x$q",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
}
|
||||
val q = quantityOf(p.id)
|
||||
if (q > 0) Text("已加购 x$q", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -217,9 +268,7 @@ private fun ProductListScreen(
|
||||
@Composable
|
||||
private fun ProductDetailScreen(
|
||||
product: Product?,
|
||||
isFavorite: Boolean,
|
||||
onBack: () -> Unit,
|
||||
onToggleFavorite: () -> Unit,
|
||||
quantity: Int,
|
||||
onAdd: (Product) -> Unit
|
||||
) {
|
||||
if (product == null) {
|
||||
@@ -227,82 +276,124 @@ private fun ProductDetailScreen(
|
||||
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 "收藏")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
tonalElevation = 2.dp,
|
||||
shape = RoundedCornerShape(14.dp)
|
||||
) {
|
||||
Column(Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
ProductCover(product.imageUrl)
|
||||
Text(product.title, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)
|
||||
PriceTag(product.price)
|
||||
Text(product.description)
|
||||
if (quantity > 0) {
|
||||
Text("当前已加购:$quantity", color = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Button(onClick = { onAdd(product) }, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("加入购物车")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CartScreen(
|
||||
cartState: CartState,
|
||||
items: List<CartItem>,
|
||||
totalPrice: Double,
|
||||
onInc: (String) -> Unit,
|
||||
onDec: (String) -> Unit,
|
||||
onRemove: (String) -> Unit,
|
||||
onClear: () -> Unit
|
||||
onClear: () -> Unit,
|
||||
onCheckout: () -> Unit
|
||||
) {
|
||||
Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
if (cartState.items.isNotEmpty()) {
|
||||
OutlinedButton(onClick = onClear) { Text("清空购物车") }
|
||||
}
|
||||
|
||||
if (cartState.items.isEmpty()) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp)
|
||||
) {
|
||||
if (items.isEmpty()) {
|
||||
EmptyState("购物车为空")
|
||||
} else {
|
||||
LazyColumn(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(cartState.items) { item ->
|
||||
LazyColumn(
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
contentPadding = PaddingValues(bottom = 96.dp)
|
||||
) {
|
||||
lazyListItems(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)}")
|
||||
Text(item.title, fontWeight = FontWeight.Medium)
|
||||
Text("¥${formatPrice(item.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("移除") }
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
SmallOpButton("-") { onDec(item.productId) }
|
||||
Text(" ${item.quantity} ")
|
||||
SmallOpButton("+") { onInc(item.productId) }
|
||||
Spacer(Modifier.width(8.dp))
|
||||
OutlinedButton(onClick = { onRemove(item.productId) }) { Text("移除") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Text("总件数:${cartState.totalCount}")
|
||||
Text("合计:¥${formatPrice(cartState.totalPrice)}", style = MaterialTheme.typography.titleMedium)
|
||||
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(12.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column {
|
||||
Text("总件数:${items.sumOf { it.quantity }}")
|
||||
Text("合计:¥${formatPrice(totalPrice)}", fontWeight = FontWeight.Bold)
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(onClick = onClear) { Text("清空") }
|
||||
Button(onClick = onCheckout) { Text("结算") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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")
|
||||
}
|
||||
private fun OrderScreen(orders: List<ShopOrder>) {
|
||||
if (orders.isEmpty()) {
|
||||
EmptyState("还没有订单")
|
||||
return
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp)
|
||||
) {
|
||||
lazyListItems(orders) { order ->
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("订单号:${order.orderId}", fontWeight = FontWeight.Bold)
|
||||
Text("状态:${order.status}")
|
||||
Text("总价:¥${formatPrice(order.totalPrice)}")
|
||||
Text("商品数:${order.items.sumOf { it.quantity }}")
|
||||
order.items.forEach { item ->
|
||||
Text("- ${item.title} x${item.quantity}")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -310,10 +401,77 @@ private fun FavoriteScreen(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ProductCover(url: String) {
|
||||
val coverModifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(150.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
|
||||
if (url.isNotBlank()) {
|
||||
SubcomposeAsyncImage(
|
||||
model = url,
|
||||
contentDescription = null,
|
||||
modifier = coverModifier,
|
||||
contentScale = ContentScale.Crop,
|
||||
loading = {
|
||||
Image(
|
||||
painter = painterResource(id = R.drawable.course_cover_default),
|
||||
contentDescription = null,
|
||||
modifier = coverModifier,
|
||||
contentScale = ContentScale.Crop
|
||||
)
|
||||
},
|
||||
error = {
|
||||
Image(
|
||||
painter = painterResource(id = R.drawable.course_cover_default),
|
||||
contentDescription = null,
|
||||
modifier = coverModifier,
|
||||
contentScale = ContentScale.Crop
|
||||
)
|
||||
},
|
||||
success = { SubcomposeAsyncImageContent() }
|
||||
)
|
||||
} else {
|
||||
Image(
|
||||
painter = painterResource(id = R.drawable.course_cover_default),
|
||||
contentDescription = null,
|
||||
modifier = coverModifier,
|
||||
contentScale = ContentScale.Crop
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SmallOpButton(text: String, onClick: () -> Unit) {
|
||||
OutlinedButton(onClick = onClick) {
|
||||
Text(text)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PriceTag(price: Double) {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.primaryContainer,
|
||||
shape = RoundedCornerShape(10.dp)
|
||||
) {
|
||||
Text(
|
||||
text = "¥${formatPrice(price)}",
|
||||
modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp),
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
fontWeight = FontWeight.SemiBold
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EmptyState(text: String) {
|
||||
Box(Modifier.fillMaxSize().padding(24.dp)) {
|
||||
Text(text, style = MaterialTheme.typography.bodyLarge)
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text("🧺", style = MaterialTheme.typography.headlineLarge)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(text, style = MaterialTheme.typography.bodyLarge)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.example.minishop
|
||||
|
||||
import com.example.minishop.network.ProductApi
|
||||
import com.example.minishop.repository.ProductRepository
|
||||
import org.koin.androidx.viewmodel.dsl.viewModel
|
||||
import org.koin.core.context.GlobalContext
|
||||
import org.koin.core.context.startKoin
|
||||
import org.koin.dsl.module
|
||||
|
||||
val appModule = module {
|
||||
single { ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false) }
|
||||
single { ProductRepository(api = get()) }
|
||||
viewModel { ShopViewModel(productRepository = get()) }
|
||||
}
|
||||
|
||||
fun initAppKoin() {
|
||||
if (GlobalContext.getOrNull() != null) return
|
||||
startKoin {
|
||||
modules(appModule)
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,13 @@ package com.example.minishop
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import com.example.minishop.db.initAppContext
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
initAppContext(applicationContext)
|
||||
initAppKoin()
|
||||
setContent {
|
||||
App()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
package com.example.minishop
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.lifecycle.ViewModel
|
||||
import com.example.minishop.cart.CartItem
|
||||
import com.example.minishop.cart.CartRepository
|
||||
import com.example.minishop.db.createShopDatabase
|
||||
import com.example.minishop.model.Product
|
||||
import com.example.minishop.order.OrderRepository
|
||||
import com.example.minishop.order.ShopOrder
|
||||
import com.example.minishop.repository.ProductRepository
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
sealed interface ProductListIntent {
|
||||
data object Load : ProductListIntent
|
||||
data object Retry : ProductListIntent
|
||||
data class AddToCart(val product: Product) : ProductListIntent
|
||||
data class Search(val query: String) : ProductListIntent
|
||||
}
|
||||
|
||||
sealed interface ProductListState {
|
||||
data object Loading : ProductListState
|
||||
data class Success(val products: List<Product>) : ProductListState
|
||||
data class Error(val message: String) : ProductListState
|
||||
data object Empty : ProductListState
|
||||
}
|
||||
|
||||
data class ShopUiState(
|
||||
val currentTab: Tab = Tab.Home,
|
||||
val inDetail: Boolean = false,
|
||||
val selectedProductId: String? = null,
|
||||
val query: String = "",
|
||||
val products: List<Product> = emptyList(),
|
||||
val productListState: ProductListState = ProductListState.Loading,
|
||||
val cartItems: List<CartItem> = emptyList(),
|
||||
val totalCount: Int = 0,
|
||||
val totalPrice: Double = 0.0,
|
||||
val orders: List<ShopOrder> = emptyList()
|
||||
)
|
||||
|
||||
class ShopViewModel(
|
||||
private val productRepository: ProductRepository,
|
||||
) : ViewModel() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||
|
||||
private val database = createShopDatabase()
|
||||
private val cartRepository = CartRepository(database)
|
||||
private val orderRepository = OrderRepository(database)
|
||||
|
||||
var uiState by mutableStateOf(ShopUiState())
|
||||
private set
|
||||
|
||||
val filteredProducts: List<Product>
|
||||
get() {
|
||||
val normalized = uiState.query.trim()
|
||||
return if (normalized.isBlank()) {
|
||||
uiState.products
|
||||
} else {
|
||||
uiState.products.filter {
|
||||
it.title.contains(normalized, ignoreCase = true) ||
|
||||
it.description.contains(normalized, ignoreCase = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val selectedProduct: Product?
|
||||
get() = uiState.products.firstOrNull { it.id == uiState.selectedProductId }
|
||||
|
||||
init {
|
||||
dispatch(ProductListIntent.Load)
|
||||
syncCart()
|
||||
syncOrders()
|
||||
}
|
||||
|
||||
fun dispatch(intent: ProductListIntent) {
|
||||
when (intent) {
|
||||
ProductListIntent.Load,
|
||||
ProductListIntent.Retry -> refreshProducts()
|
||||
|
||||
is ProductListIntent.Search -> {
|
||||
uiState = uiState.copy(query = intent.query)
|
||||
}
|
||||
|
||||
is ProductListIntent.AddToCart -> {
|
||||
cartRepository.add(intent.product)
|
||||
syncCart()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun refreshProducts() {
|
||||
scope.launch {
|
||||
uiState = uiState.copy(productListState = ProductListState.Loading)
|
||||
|
||||
runCatching { productRepository.getProducts() }
|
||||
.onSuccess { list ->
|
||||
uiState = uiState.copy(
|
||||
products = list,
|
||||
productListState = if (list.isEmpty()) {
|
||||
ProductListState.Empty
|
||||
} else {
|
||||
ProductListState.Success(list)
|
||||
}
|
||||
)
|
||||
syncCart()
|
||||
}
|
||||
.onFailure {
|
||||
uiState = uiState.copy(
|
||||
productListState = ProductListState.Error(it.message ?: "加载失败")
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onQueryChange(value: String) {
|
||||
dispatch(ProductListIntent.Search(value))
|
||||
}
|
||||
|
||||
fun selectTab(tab: Tab) {
|
||||
uiState = uiState.copy(currentTab = tab)
|
||||
}
|
||||
|
||||
fun openDetail(product: Product) {
|
||||
uiState = uiState.copy(inDetail = true, selectedProductId = product.id)
|
||||
}
|
||||
|
||||
fun closeDetail() {
|
||||
uiState = uiState.copy(inDetail = false)
|
||||
}
|
||||
|
||||
fun quantityOf(productId: String): Int =
|
||||
uiState.cartItems.firstOrNull { it.productId == productId }?.quantity ?: 0
|
||||
|
||||
fun addToCart(product: Product): String {
|
||||
dispatch(ProductListIntent.AddToCart(product))
|
||||
return "已加入购物车"
|
||||
}
|
||||
|
||||
fun increase(productId: String) {
|
||||
cartRepository.increase(productId)
|
||||
syncCart()
|
||||
}
|
||||
|
||||
fun decrease(productId: String) {
|
||||
cartRepository.decrease(productId)
|
||||
syncCart()
|
||||
}
|
||||
|
||||
fun remove(productId: String) {
|
||||
cartRepository.remove(productId)
|
||||
syncCart()
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
cartRepository.clear()
|
||||
syncCart()
|
||||
}
|
||||
|
||||
fun checkout(): String {
|
||||
val cartItems = cartRepository.items()
|
||||
if (cartItems.isEmpty()) {
|
||||
return "购物车为空"
|
||||
}
|
||||
|
||||
val order = orderRepository.createOrder(cartItems)
|
||||
?: return "创建订单失败"
|
||||
|
||||
cartRepository.clear()
|
||||
syncCart()
|
||||
syncOrders()
|
||||
uiState = uiState.copy(currentTab = Tab.Orders)
|
||||
return "下单成功,订单号:${order.orderId}"
|
||||
}
|
||||
|
||||
private fun syncCart() {
|
||||
val items = cartRepository.items()
|
||||
uiState = uiState.copy(
|
||||
cartItems = items,
|
||||
totalCount = items.sumOf { it.quantity },
|
||||
totalPrice = items.sumOf { it.price * it.quantity }
|
||||
)
|
||||
}
|
||||
|
||||
private fun syncOrders() {
|
||||
uiState = uiState.copy(orders = orderRepository.getOrders())
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
scope.cancel()
|
||||
super.onCleared()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="600dp"
|
||||
android:height="360dp"
|
||||
android:viewportWidth="600"
|
||||
android:viewportHeight="360">
|
||||
|
||||
<path
|
||||
android:fillColor="#4F46E5"
|
||||
android:pathData="M0,0h600v360h-600z" />
|
||||
|
||||
<path
|
||||
android:fillColor="#0EA5E9"
|
||||
android:fillAlpha="0.35"
|
||||
android:pathData="M-40,260C80,180 170,320 280,250C380,186 470,290 640,210L640,360L-40,360Z" />
|
||||
|
||||
<path
|
||||
android:fillColor="#06B6D4"
|
||||
android:fillAlpha="0.45"
|
||||
android:pathData="M-30,170C80,120 180,230 270,180C380,120 470,210 630,140L630,0L-30,0Z" />
|
||||
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:fillAlpha="0.92"
|
||||
android:pathData="M246,124h108a12,12 0 0 1 12,12v88a12,12 0 0 1 -12,12h-108a12,12 0 0 1 -12,-12v-88a12,12 0 0 1 12,-12z" />
|
||||
|
||||
<path
|
||||
android:fillColor="#4F46E5"
|
||||
android:pathData="M274,152h52a8,8 0 0 1 8,8v40a8,8 0 0 1 -8,8h-52a8,8 0 0 1 -8,-8v-40a8,8 0 0 1 8,-8z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,411 @@
|
||||
# KMP Mini Shopping 纯UI离线版(Android)
|
||||
|
||||
> 用途:课堂一步一步带写 UI,不依赖网络、不依赖 Repository/ViewModel。
|
||||
> 方式:直接替换 `composeApp/src/androidMain/kotlin/com/example/minishop/App.kt`。
|
||||
|
||||
```kotlin
|
||||
package com.example.minishop
|
||||
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
|
||||
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
|
||||
import androidx.compose.foundation.lazy.staggeredgrid.items as staggeredItems
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
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.Surface
|
||||
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.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
enum class Tab { Home, Cart }
|
||||
|
||||
data class UiProduct(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val price: Double,
|
||||
val description: String,
|
||||
val imageUrl: String = ""
|
||||
)
|
||||
|
||||
data class UiCartItem(
|
||||
val productId: String,
|
||||
val quantity: Int
|
||||
)
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun App() {
|
||||
MaterialTheme {
|
||||
var currentTab by remember { mutableStateOf(Tab.Home) }
|
||||
var inDetail by remember { mutableStateOf(false) }
|
||||
var selected by remember { mutableStateOf<UiProduct?>(null) }
|
||||
var query by remember { mutableStateOf("") }
|
||||
|
||||
val products = remember { demoProducts() }
|
||||
var cartMap by remember { mutableStateOf<Map<String, Int>>(emptyMap()) }
|
||||
|
||||
val filtered = remember(products, query) {
|
||||
val q = query.trim()
|
||||
if (q.isBlank()) products
|
||||
else products.filter {
|
||||
it.title.contains(q, true) || it.description.contains(q, true)
|
||||
}
|
||||
}
|
||||
|
||||
val cartItems = remember(cartMap) {
|
||||
cartMap.map { UiCartItem(productId = it.key, quantity = it.value) }
|
||||
}
|
||||
val productMap = remember(products) { products.associateBy { it.id } }
|
||||
val totalCount = cartItems.sumOf { it.quantity }
|
||||
val totalPrice = cartItems.sumOf { item ->
|
||||
(productMap[item.productId]?.price ?: 0.0) * item.quantity
|
||||
}
|
||||
|
||||
fun add(id: String) {
|
||||
cartMap = cartMap.toMutableMap().apply {
|
||||
this[id] = (this[id] ?: 0) + 1
|
||||
}
|
||||
}
|
||||
|
||||
fun inc(id: String) = add(id)
|
||||
|
||||
fun dec(id: String) {
|
||||
cartMap = cartMap.toMutableMap().apply {
|
||||
val old = this[id] ?: return
|
||||
if (old <= 1) remove(id) else this[id] = old - 1
|
||||
}
|
||||
}
|
||||
|
||||
fun remove(id: String) {
|
||||
cartMap = cartMap.toMutableMap().apply { remove(id) }
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
cartMap = emptyMap()
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = {
|
||||
Text(
|
||||
when {
|
||||
inDetail -> "商品详情"
|
||||
currentTab == Tab.Home -> "Mini Shopping(纯UI)"
|
||||
else -> "购物车"
|
||||
}
|
||||
)
|
||||
},
|
||||
actions = {
|
||||
if (inDetail) {
|
||||
TextButton(onClick = { inDetail = false }) { Text("返回") }
|
||||
} else {
|
||||
Text(
|
||||
text = "共 $totalCount 件",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
modifier = Modifier.padding(end = 12.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
if (!inDetail) {
|
||||
NavigationBar {
|
||||
NavigationBarItem(
|
||||
selected = currentTab == Tab.Home,
|
||||
onClick = { currentTab = Tab.Home },
|
||||
icon = { Text("🏠") },
|
||||
label = { Text("商品") }
|
||||
)
|
||||
NavigationBarItem(
|
||||
selected = currentTab == Tab.Cart,
|
||||
onClick = { currentTab = Tab.Cart },
|
||||
icon = { Text("🛒") },
|
||||
label = { Text("购物车($totalCount)") }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
) { padding ->
|
||||
Box(
|
||||
Modifier
|
||||
.padding(padding)
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.surface)
|
||||
) {
|
||||
when {
|
||||
inDetail -> DetailScreen(
|
||||
product = selected,
|
||||
quantity = selected?.let { cartMap[it.id] ?: 0 } ?: 0,
|
||||
onAdd = { add(it.id) }
|
||||
)
|
||||
|
||||
currentTab == Tab.Home -> HomeScreen(
|
||||
products = filtered,
|
||||
totalProducts = products.size,
|
||||
query = query,
|
||||
quantityOf = { id -> cartMap[id] ?: 0 },
|
||||
onQueryChange = { query = it },
|
||||
onAdd = { add(it.id) },
|
||||
onClick = {
|
||||
selected = it
|
||||
inDetail = true
|
||||
}
|
||||
)
|
||||
|
||||
else -> CartScreen(
|
||||
items = cartItems,
|
||||
productMap = productMap,
|
||||
totalPrice = totalPrice,
|
||||
onInc = ::inc,
|
||||
onDec = ::dec,
|
||||
onRemove = ::remove,
|
||||
onClear = ::clear
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun HomeScreen(
|
||||
products: List<UiProduct>,
|
||||
totalProducts: Int,
|
||||
query: String,
|
||||
quantityOf: (String) -> Int,
|
||||
onQueryChange: (String) -> Unit,
|
||||
onAdd: (UiProduct) -> Unit,
|
||||
onClick: (UiProduct) -> Unit
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp)
|
||||
) {
|
||||
OutlinedTextField(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
value = query,
|
||||
onValueChange = onQueryChange,
|
||||
singleLine = true,
|
||||
label = { Text("搜索课程") }
|
||||
)
|
||||
|
||||
Text("共 $totalProducts 条 · 当前显示 ${products.size} 条")
|
||||
|
||||
if (products.isEmpty()) {
|
||||
EmptyState("没有匹配的商品")
|
||||
} else {
|
||||
LazyVerticalStaggeredGrid(
|
||||
columns = StaggeredGridCells.Fixed(2),
|
||||
verticalItemSpacing = 10.dp,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
modifier = Modifier.fillMaxSize()
|
||||
) {
|
||||
staggeredItems(products, key = { it.id }) { p ->
|
||||
ElevatedCard(onClick = { onClick(p) }, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(10.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Cover(p.imageUrl)
|
||||
Text(p.title, fontWeight = FontWeight.SemiBold)
|
||||
PriceTag(p.price)
|
||||
Text(p.description, maxLines = 3)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Button(onClick = { onAdd(p) }) { Text("加购") }
|
||||
Spacer(Modifier.width(8.dp))
|
||||
val q = quantityOf(p.id)
|
||||
if (q > 0) Text("x$q", color = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DetailScreen(
|
||||
product: UiProduct?,
|
||||
quantity: Int,
|
||||
onAdd: (UiProduct) -> Unit
|
||||
) {
|
||||
if (product == null) {
|
||||
EmptyState("商品不存在")
|
||||
return
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
Cover(product.imageUrl)
|
||||
Text(product.title, style = MaterialTheme.typography.headlineSmall)
|
||||
PriceTag(product.price)
|
||||
Text(product.description)
|
||||
if (quantity > 0) Text("当前已加购:$quantity")
|
||||
Button(onClick = { onAdd(product) }, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("加入购物车")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CartScreen(
|
||||
items: List<UiCartItem>,
|
||||
productMap: Map<String, UiProduct>,
|
||||
totalPrice: Double,
|
||||
onInc: (String) -> Unit,
|
||||
onDec: (String) -> Unit,
|
||||
onRemove: (String) -> Unit,
|
||||
onClear: () -> Unit
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp)
|
||||
) {
|
||||
if (items.isEmpty()) {
|
||||
EmptyState("购物车为空")
|
||||
} else {
|
||||
LazyColumn(
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
contentPadding = PaddingValues(bottom = 96.dp)
|
||||
) {
|
||||
items(items) { item ->
|
||||
val p = productMap[item.productId] ?: return@items
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
Text(p.title)
|
||||
Text("¥${formatPrice(p.price * item.quantity)}")
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedButton(onClick = { onDec(p.id) }) { Text("-") }
|
||||
Text(" ${item.quantity} ")
|
||||
OutlinedButton(onClick = { onInc(p.id) }) { Text("+") }
|
||||
Spacer(Modifier.width(8.dp))
|
||||
OutlinedButton(onClick = { onRemove(p.id) }) { Text("移除") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(12.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column {
|
||||
Text("总件数:${items.sumOf { it.quantity }}")
|
||||
Text("合计:¥${formatPrice(totalPrice)}", fontWeight = FontWeight.Bold)
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(onClick = onClear) { Text("清空") }
|
||||
Button(onClick = onClear) { Text("结算(模拟)") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Cover(url: String) {
|
||||
// 纯UI课:不走网络图,直接本地占位
|
||||
Image(
|
||||
painter = painterResource(id = R.drawable.course_cover_default),
|
||||
contentDescription = null,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(150.dp)
|
||||
.clip(RoundedCornerShape(12.dp)),
|
||||
contentScale = ContentScale.Crop
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PriceTag(price: Double) {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.primaryContainer,
|
||||
shape = RoundedCornerShape(10.dp)
|
||||
) {
|
||||
Text(
|
||||
text = "¥${formatPrice(price)}",
|
||||
modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp),
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
fontWeight = FontWeight.SemiBold
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EmptyState(text: String) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text("🧺")
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun formatPrice(price: Double): String = "%.2f".format(price)
|
||||
|
||||
private fun demoProducts(): List<UiProduct> = listOf(
|
||||
UiProduct("1", "KMP 入门课", 99.0, "跨平台开发基础课程"),
|
||||
UiProduct("2", "Compose 实战课", 149.0, "Compose 多端 UI 实战"),
|
||||
UiProduct("3", "协程训练营", 129.0, "协程与 Flow 进阶"),
|
||||
UiProduct("4", "Clean 架构速成", 199.0, "从0构建可维护架构"),
|
||||
UiProduct("5", "SQLDelight 实战", 119.0, "KMP 本地数据库方案"),
|
||||
UiProduct("6", "Ktor API 实战", 159.0, "跨平台网络层搭建")
|
||||
)
|
||||
```
|
||||
@@ -0,0 +1,85 @@
|
||||
# 第6-7节课程大纲|KMP 商城:网络存储与数据层升级
|
||||
|
||||
## 第6节:KMP 商城实战——网络与存储
|
||||
|
||||
**对应 SkillMap:**
|
||||
5. 跨平台技术栈(Ktor / Settings / Serialization)
|
||||
|
||||
### 本节目标
|
||||
- 在 KMP 共享层完成网络请求与本地存储能力
|
||||
- 完成商城最小闭环:商品列表(网络)+ 购物车(存储)
|
||||
- Android 端只做展示与交互,不承载核心业务逻辑
|
||||
|
||||
### 本节内容(1~2小时)
|
||||
1. KMP 中集成 Ktor 网络
|
||||
2. 封装通用网络请求能力
|
||||
3. 商品列表接口实战(可先 Mock 后真实)
|
||||
4. 集成跨平台存储(Multiplatform Settings)
|
||||
5. 购物车数据本地持久化
|
||||
6. 数据解析(kotlinx-serialization)
|
||||
|
||||
### 课堂实战产出
|
||||
- 共享层实现:商品列表拉取 + 购物车持久化
|
||||
- Android 页面可运行:商品展示、加购、重启后数据不丢失
|
||||
|
||||
### 课后作业(≤2小时)
|
||||
- 完成商品详情接口
|
||||
- 存储优化:删除 / 数量修改
|
||||
- 提交运行截图 + 核心代码截图
|
||||
|
||||
---
|
||||
|
||||
## 第7节:KMP 商城实战——SQL 升级 + 最小架构改造
|
||||
|
||||
**对应 SkillMap:**
|
||||
4. KMP 核心能力 + 6. 平台集成能力 + 7. 工程化与业务落地
|
||||
|
||||
### 本节定位
|
||||
第7节重点不是“大量架构理论”,而是把项目升级到更接近真实业务:
|
||||
- 数据层从 Settings 升级到 SQL(结构化存储)
|
||||
- 补齐订单最小业务闭环
|
||||
- MVI 只做最小化落地(1个核心页面)
|
||||
|
||||
### 本节目标
|
||||
- 完成第6节作业复盘并确定改造点
|
||||
- 将购物车存储从 Settings 升级到 SQL
|
||||
- 完成订单最小闭环(下单后清空购物车 + 订单列表)
|
||||
- 在一个核心页面落地最小 MVI(Intent / State / Reducer)
|
||||
- 统一错误呈现,减少异常处理分散
|
||||
|
||||
### 本节内容(1~2小时)
|
||||
1. **第6节作业讲解与问题归类**
|
||||
- 高频问题:网络异常、解析失败、存储一致性
|
||||
- 从“能跑”对齐到“可维护”
|
||||
|
||||
2. **数据层升级:Settings → SQL(核心)**
|
||||
- 为什么要升级:查询、排序、扩展能力
|
||||
- 购物车表、订单表、订单明细表最小字段设计
|
||||
- Repository 改造:统一读写本地库
|
||||
|
||||
3. **订单最小闭环(核心)**
|
||||
- 从购物车生成订单(简化版)
|
||||
- 下单成功后清空购物车
|
||||
- 订单列表页展示本地下单记录
|
||||
|
||||
4. **MVI 最小化落地(补充)**
|
||||
- 仅改造一个核心页面(建议商品列表页)
|
||||
- Intent:加载/重试/加购
|
||||
- State:Loading / Success / Error / Empty
|
||||
- Reducer:状态统一收敛
|
||||
|
||||
5. **统一错误呈现(补充)**
|
||||
- 共享层统一错误结构(Success / Error)
|
||||
- UI 层仅消费标准错误,避免异常处理分散
|
||||
- 统一重试入口与错误提示文案
|
||||
|
||||
### 课堂实战产出
|
||||
- 完成购物车与订单的 SQL 本地持久化
|
||||
- 完成“购物车→下单→订单列表”闭环演示
|
||||
- 完成 1 个核心页面的最小 MVI 改造
|
||||
- 完成统一错误呈现的基础收口
|
||||
|
||||
### 课后作业(≤2小时)
|
||||
- 增加订单状态字段并支持筛选(全部/待支付/已完成)
|
||||
- 增加手动刷新与重试入口,完善错误提示
|
||||
- 提交运行录屏(包含加购、下单、订单列表展示)
|
||||
Binary file not shown.
@@ -0,0 +1,404 @@
|
||||
# 第6节|KMP 商城实操讲稿
|
||||
## 主题:shared 共享层网络 + 本地持久化(把数据链路真正跑通)
|
||||
|
||||
> 按步骤完成后可稳定实现:
|
||||
> 1)商品列表加载;2)加入购物车;3)重启后购物车不丢。
|
||||
|
||||
---
|
||||
|
||||
## 一、课前准备
|
||||
|
||||
### 1. 环境
|
||||
- JDK 17
|
||||
- Android Studio 最新稳定版
|
||||
- 可运行 Android 模拟器或真机
|
||||
|
||||
### 2. 项目结构检查
|
||||
确认项目是 KMP Wizard 标准结构:
|
||||
|
||||
```text
|
||||
kmp-mini-shopping/
|
||||
├─ composeApp/ # Android UI 层
|
||||
├─ shared/ # 共享业务层
|
||||
│ ├─ src/commonMain
|
||||
│ ├─ src/androidMain
|
||||
│ └─ src/iosMain
|
||||
└─ docs/
|
||||
```
|
||||
|
||||
### 3. AndroidManifest 网络权限
|
||||
`composeApp/src/androidMain/AndroidManifest.xml`
|
||||
|
||||
```xml
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
```
|
||||
|
||||
> 课程已统一使用 HTTPS 地址:`https://shopneu.hmos.site`。
|
||||
> 仅当你改回本地 HTTP 联调时,才需要 `usesCleartextTraffic=true`。
|
||||
|
||||
---
|
||||
|
||||
## 二、本节目标(开场 2 分钟)
|
||||
|
||||
今天只做三件事:
|
||||
|
||||
1. 在 `shared` 实现商品网络请求(Ktor)
|
||||
2. 在 `shared` 实现购物车持久化(Settings)
|
||||
3. Android 页面只做“展示 + 调用 shared”
|
||||
|
||||
> 强调:业务规则都在 shared,不写死在 Android 页面里。
|
||||
|
||||
---
|
||||
|
||||
## 三、依赖配置(第1段:10分钟)
|
||||
|
||||
> 目标:让 shared 能发请求、能序列化、能存本地。
|
||||
|
||||
### 1. `shared/build.gradle.kts`
|
||||
直接在 `kotlin { sourceSets { ... } }` 里按下面写(可照抄):
|
||||
|
||||
```kotlin
|
||||
kotlin {
|
||||
sourceSets {
|
||||
all {
|
||||
languageSettings.optIn("kotlinx.cinterop.ExperimentalForeignApi")
|
||||
languageSettings.optIn("kotlin.experimental.ExperimentalObjCName")
|
||||
}
|
||||
|
||||
commonMain.dependencies {
|
||||
implementation("io.ktor:ktor-client-core:3.1.3")
|
||||
implementation("io.ktor:ktor-client-content-negotiation:3.1.3")
|
||||
implementation("io.ktor:ktor-serialization-kotlinx-json:3.1.3")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.8.1")
|
||||
implementation("com.russhwolf:multiplatform-settings-no-arg:1.1.1")
|
||||
}
|
||||
|
||||
androidMain.dependencies {
|
||||
implementation("io.ktor:ktor-client-okhttp:3.1.3")
|
||||
}
|
||||
|
||||
iosMain.dependencies {
|
||||
implementation("io.ktor:ktor-client-darwin:3.1.3")
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> 如果你项目当前版本不一致,以你项目里已锁定版本为准。
|
||||
|
||||
补充说明(这两行为什么要加):
|
||||
|
||||
- `languageSettings.optIn("kotlinx.cinterop.ExperimentalForeignApi")`
|
||||
- 用于允许 iOS/Native 侧 C 互操作相关的实验 API(常见于 Darwin/平台互操作场景)。
|
||||
- `languageSettings.optIn("kotlin.experimental.ExperimentalObjCName")`
|
||||
- 用于允许 `@ObjCName` 等和 Objective-C/Swift 导出命名相关的实验能力。
|
||||
|
||||
这两行主要是为了减少 KMP iOS 侧编译期 opt-in 警告/报错,保证多端示例在课堂环境更稳定。
|
||||
|
||||
### 2. Ktor 官方文档(课堂可直接贴)
|
||||
- Ktor Multiplatform Client 官方教程:
|
||||
`https://ktor.io/docs/client-create-multiplatform-application.html`
|
||||
- Ktor Serialization 官方说明(ContentNegotiation/JSON 的用途):
|
||||
`https://ktor.io/docs/server-serialization.html`
|
||||
|
||||
### 2.1 课程统一后端地址(已部署)
|
||||
- 线上地址:`https://shopneu.hmos.site`
|
||||
- 商品接口:`https://shopneu.hmos.site/api/products`(推荐)
|
||||
|
||||
Android 端 `baseUrl` 建议写:
|
||||
|
||||
```kotlin
|
||||
ProductApi(baseUrl = "https://shopneu.hmos.site/api", useMock = false)
|
||||
```
|
||||
|
||||
### 3. `content-negotiation` 是干什么的?(给学生讲)
|
||||
`ktor-client-content-negotiation` + `ktor-serialization-kotlinx-json` 这两个依赖,
|
||||
就是让 Ktor 能把接口返回的 JSON 自动反序列化成 Kotlin 数据类(例如 `List<Product>`)。
|
||||
|
||||
对应代码就是:
|
||||
|
||||
```kotlin
|
||||
install(ContentNegotiation) {
|
||||
json(Json {
|
||||
ignoreUnknownKeys = true
|
||||
isLenient = true
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
如果不加这两个依赖,`body<List<Product>>()` 这类写法会失败(无法自动解析 JSON)。
|
||||
|
||||
另外,`ignoreUnknownKeys = true` 的作用是:
|
||||
- 当后端返回了“数据类里未定义的字段”时,不报错,直接忽略。
|
||||
- 适合课堂联调和后端字段可能变动的阶段,提升稳定性。
|
||||
|
||||
示例:
|
||||
- `Product` 只定义了 `id/title`
|
||||
- 后端额外返回 `tag/extra`
|
||||
- 开启 `ignoreUnknownKeys = true` 后,`id/title` 仍可正常解析。
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 四、共享模型(第2段:10分钟)
|
||||
|
||||
### Step 1:商品模型
|
||||
文件:`shared/src/commonMain/kotlin/com/example/minishop/model/Product.kt`
|
||||
|
||||
```kotlin
|
||||
package com.example.minishop.model
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class Product(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val price: Double,
|
||||
val description: String,
|
||||
val imageUrl: String = ""
|
||||
)
|
||||
```
|
||||
|
||||
### Step 2:购物车项模型
|
||||
文件:`shared/src/commonMain/kotlin/com/example/minishop/cart/CartItem.kt`
|
||||
|
||||
```kotlin
|
||||
package com.example.minishop.cart
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class CartItem(
|
||||
val productId: String,
|
||||
val quantity: Int
|
||||
)
|
||||
```
|
||||
|
||||
**课堂检查点:**
|
||||
- 两个模型都加了 `@Serializable`
|
||||
- `imageUrl` 给默认值,后续缺图不崩
|
||||
|
||||
---
|
||||
|
||||
## 五、网络层(第3段:20分钟)
|
||||
|
||||
### Step 3:HttpClient 工厂(commonMain)
|
||||
文件:`shared/.../network/HttpClientFactory.kt`
|
||||
|
||||
```kotlin
|
||||
package com.example.minishop.network
|
||||
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.engine.HttpClientEngine
|
||||
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.serialization.kotlinx.json.json
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
expect fun provideHttpEngine(): HttpClientEngine
|
||||
|
||||
fun createHttpClient(): HttpClient = HttpClient(provideHttpEngine()) {
|
||||
install(ContentNegotiation) {
|
||||
json(Json {
|
||||
ignoreUnknownKeys = true
|
||||
isLenient = true
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 4:Android 实现 actual
|
||||
文件:`shared/src/androidMain/.../network/HttpClientFactory.android.kt`
|
||||
|
||||
```kotlin
|
||||
package com.example.minishop.network
|
||||
|
||||
import io.ktor.client.engine.HttpClientEngine
|
||||
import io.ktor.client.engine.okhttp.OkHttp
|
||||
|
||||
actual fun provideHttpEngine(): HttpClientEngine = OkHttp.create()
|
||||
```
|
||||
|
||||
### Step 5:商品 API
|
||||
文件:`shared/.../network/ProductApi.kt`
|
||||
|
||||
```kotlin
|
||||
package com.example.minishop.network
|
||||
|
||||
import com.example.minishop.model.Product
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.call.body
|
||||
import io.ktor.client.request.get
|
||||
|
||||
class ProductApi(
|
||||
private val baseUrl: String,
|
||||
private val useMock: Boolean = true,
|
||||
private val client: HttpClient = createHttpClient()
|
||||
) {
|
||||
suspend fun fetchProducts(): List<Product> {
|
||||
if (useMock) return mockProducts()
|
||||
return client.get("$baseUrl/products").body()
|
||||
}
|
||||
|
||||
private fun mockProducts(): List<Product> = listOf(
|
||||
Product("1", "KMP 入门课", 99.0, "跨平台开发基础课程", "https://picsum.photos/seed/kmp1/600/360"),
|
||||
Product("2", "Compose 实战课", 149.0, "Compose 多端 UI 实战", "https://picsum.photos/seed/kmp2/600/360")
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**课堂检查点:**
|
||||
- `useMock=true` 时,不依赖后端也能讲
|
||||
- `useMock=false` 时,准备第7节真机联调
|
||||
|
||||
---
|
||||
|
||||
## 六、购物车持久化(第4段:20分钟)
|
||||
|
||||
### Step 6:CartStorage
|
||||
文件:`shared/.../cart/CartStorage.kt`
|
||||
|
||||
```kotlin
|
||||
package com.example.minishop.cart
|
||||
|
||||
import com.russhwolf.settings.Settings
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
class CartStorage(
|
||||
private val settings: Settings = Settings(),
|
||||
private val json: Json = Json { ignoreUnknownKeys = true }
|
||||
) {
|
||||
private val key = "cart_items"
|
||||
|
||||
fun load(): List<CartItem> {
|
||||
val raw = settings.getStringOrNull(key) ?: return emptyList()
|
||||
return runCatching { json.decodeFromString<List<CartItem>>(raw) }
|
||||
.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
fun save(items: List<CartItem>) {
|
||||
settings.putString(key, json.encodeToString(items))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 7:CartRepository
|
||||
文件:`shared/.../cart/CartRepository.kt`
|
||||
|
||||
```kotlin
|
||||
package com.example.minishop.cart
|
||||
|
||||
class CartRepository(
|
||||
private val storage: CartStorage = CartStorage()
|
||||
) {
|
||||
private val map = storage.load().associateBy { it.productId }.toMutableMap()
|
||||
|
||||
fun items(): List<CartItem> = map.values.sortedBy { it.productId }
|
||||
|
||||
fun add(productId: String) {
|
||||
val old = map[productId]
|
||||
map[productId] = if (old == null) CartItem(productId, 1) else old.copy(quantity = old.quantity + 1)
|
||||
persist()
|
||||
}
|
||||
|
||||
fun increase(productId: String) {
|
||||
val old = map[productId] ?: return
|
||||
map[productId] = old.copy(quantity = old.quantity + 1)
|
||||
persist()
|
||||
}
|
||||
|
||||
fun decrease(productId: String) {
|
||||
val old = map[productId] ?: return
|
||||
if (old.quantity <= 1) map.remove(productId) else map[productId] = old.copy(quantity = old.quantity - 1)
|
||||
persist()
|
||||
}
|
||||
|
||||
fun remove(productId: String) {
|
||||
map.remove(productId)
|
||||
persist()
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
map.clear()
|
||||
persist()
|
||||
}
|
||||
|
||||
private fun persist() = storage.save(items())
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 七、仓储层(第5段:10分钟)
|
||||
|
||||
### Step 8:ProductRepository
|
||||
文件:`shared/.../repository/ProductRepository.kt`
|
||||
|
||||
```kotlin
|
||||
package com.example.minishop.repository
|
||||
|
||||
import com.example.minishop.model.Product
|
||||
import com.example.minishop.network.ProductApi
|
||||
|
||||
class ProductRepository(
|
||||
private val api: ProductApi,
|
||||
private val fallback: List<Product> = emptyList()
|
||||
) {
|
||||
suspend fun getProducts(): List<Product> = runCatching { api.fetchProducts() }.getOrDefault(fallback)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 八、Android 接最小 UI(第6段:20分钟)
|
||||
|
||||
> 本节只接“能跑通”的最小 UI:
|
||||
> - 列表显示
|
||||
> - 加购按钮
|
||||
> - 顶部总件数
|
||||
|
||||
### Step 9:在 `App.kt` 做最小调用
|
||||
思路:
|
||||
1. `remember` 一个 `ProductRepository`
|
||||
2. `LaunchedEffect(Unit)` 拉列表
|
||||
3. 点击加购调用 `cartRepository.add(product.id)`
|
||||
4. 总件数用 `cartRepository.items().sumOf { it.quantity }`
|
||||
|
||||
---
|
||||
|
||||
## 九、本节常见报错与处理
|
||||
|
||||
### 1)`Unresolved reference: ContentNegotiation`(Ktor Client)
|
||||
检查两件事:
|
||||
- 依赖是否存在:`ktor-client-content-negotiation` 与 `ktor-serialization-kotlinx-json`
|
||||
- import 是否正确:
|
||||
```kotlin
|
||||
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.serialization.kotlinx.json.json
|
||||
```
|
||||
|
||||
### 2)接口可在浏览器打开,但 App 仍无数据
|
||||
- `baseUrl` 是否为:`https://shopneu.hmos.site/api`
|
||||
- 是否误开了搜索过滤(输入框残留空格/关键词)
|
||||
|
||||
### 3)商品返回有数据,但 UI 显示“没有匹配”
|
||||
- 搜索词先 `trim()`
|
||||
- 先打印“服务总数 vs 当前显示数”定位是否是过滤导致
|
||||
|
||||
---
|
||||
|
||||
## 十、本节验收(最后5分钟)
|
||||
|
||||
- [ ] shared 有 ProductApi / ProductRepository / CartRepository
|
||||
- [ ] Android 列表能显示
|
||||
- [ ] 加购后总件数变化
|
||||
- [ ] 退出重开购物车仍在
|
||||
|
||||
---
|
||||
|
||||
## 十一、作业(课后)
|
||||
|
||||
1. 列表加搜索
|
||||
2. 购物车加清空
|
||||
3. 提交:两张截图(列表+购物车)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,634 @@
|
||||
# 第7节补充|Koin 最小注入演示
|
||||
## 主题:只用一小段依赖注入,演示 Koin 怎么接进现有项目
|
||||
|
||||
> 这一份补充文档不追求“全项目都改成依赖注入”,
|
||||
> 只演示最小可理解的一段:
|
||||
>
|
||||
> `ProductApi -> ProductRepository -> ShopViewModel`
|
||||
>
|
||||
> 这样做的目的不是大重构,
|
||||
> 而是让学生先看懂:
|
||||
> 1. Koin 是干什么的
|
||||
> 2. 在 KMP / Compose Android 项目里怎么引用
|
||||
> 3. 怎么把“手动 new 对象”改成“由容器提供对象”
|
||||
|
||||
---
|
||||
|
||||
# 一、先讲清楚:Koin 是什么
|
||||
|
||||
## 1. Koin 是干什么的
|
||||
Koin 是一个 Kotlin 生态里很常见的**依赖注入(Dependency Injection, DI)**库。
|
||||
|
||||
它解决的核心问题是:
|
||||
|
||||
> **对象不要在业务类里到处自己 new,
|
||||
> 而是统一交给一个容器来创建和提供。**
|
||||
|
||||
比如以前我们可能在 `ShopViewModel` 里直接写:
|
||||
|
||||
```kotlin
|
||||
private val productRepository = ProductRepository(
|
||||
api = ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false)
|
||||
)
|
||||
```
|
||||
|
||||
这种写法的缺点是:
|
||||
- ViewModel 自己决定依赖怎么创建
|
||||
- 以后如果 `ProductApi` 参数变了,要改 ViewModel
|
||||
- 如果以后想替换 mock / test 实现,也不方便
|
||||
- 对象创建逻辑散落在业务代码里
|
||||
|
||||
Koin 的思路是:
|
||||
- 把对象创建逻辑集中写在 `module` 里
|
||||
- 业务类只声明“我需要什么”
|
||||
- 容器负责把对象注入进来
|
||||
|
||||
---
|
||||
|
||||
## 2. 什么叫“依赖注入”
|
||||
比如 `ShopViewModel` 需要 `ProductRepository`,
|
||||
那 `ProductRepository` 就是它的一个**依赖**。
|
||||
|
||||
如果我们把它写成:
|
||||
|
||||
```kotlin
|
||||
class ShopViewModel(
|
||||
private val productRepository: ProductRepository,
|
||||
) : ViewModel()
|
||||
```
|
||||
|
||||
这就叫**构造函数注入**。
|
||||
|
||||
意思是:
|
||||
- `ShopViewModel` 不再自己创建 `ProductRepository`
|
||||
- 谁来创建?由外部容器(这里就是 Koin)提供
|
||||
|
||||
这是依赖注入里最常见、也最推荐的方式。
|
||||
|
||||
---
|
||||
|
||||
## 3. 为什么这里只做“最小演示”
|
||||
这次不打算把整个项目都改成 Koin,原因很简单:
|
||||
|
||||
1. 课堂演示不需要一步到位
|
||||
2. 学生第一次接触 DI,先理解一条链路最重要
|
||||
3. 先演示成功,再决定要不要扩到数据库、购物车、订单
|
||||
|
||||
所以本补充文档只改这一段:
|
||||
|
||||
- `ProductApi`
|
||||
- `ProductRepository`
|
||||
- `ShopViewModel`
|
||||
- Compose 页面如何从 Koin 拿 ViewModel
|
||||
|
||||
购物车 / 订单 / SQLDelight 先继续保持原写法,不强行一起改。
|
||||
|
||||
---
|
||||
|
||||
# 二、这个项目里怎么引用 Koin
|
||||
|
||||
## 1. Gradle 里已经有哪些 Koin 依赖
|
||||
当前项目里已经有这两类依赖:
|
||||
|
||||
### `shared/build.gradle.kts`
|
||||
```kotlin
|
||||
commonMain.dependencies {
|
||||
implementation(libs.koin.core)
|
||||
}
|
||||
```
|
||||
|
||||
这里的 `koin-core` 是 Koin 的核心能力,
|
||||
适合放在共享层或纯 Kotlin 层使用。
|
||||
|
||||
### `composeApp/build.gradle.kts`
|
||||
```kotlin
|
||||
androidMain.dependencies {
|
||||
implementation(libs.koin.androidx.compose)
|
||||
}
|
||||
```
|
||||
|
||||
这里的 `koin-androidx-compose` 是给 Android + Compose 场景用的,
|
||||
主要用于:
|
||||
- 在 Compose 中获取依赖
|
||||
- 在 Compose 中获取由 Koin 管理的 ViewModel
|
||||
|
||||
---
|
||||
|
||||
## 2. `libs.versions.toml` 里是怎么声明的
|
||||
文件路径:`gradle/libs.versions.toml`
|
||||
|
||||
当前项目里对应的是:
|
||||
|
||||
```toml
|
||||
[versions]
|
||||
koin = "4.1.0"
|
||||
|
||||
[libraries]
|
||||
koin-core = { module = "io.insert-koin:koin-core", version.ref = "koin" }
|
||||
koin-androidx-compose = { module = "io.insert-koin:koin-androidx-compose", version.ref = "koin" }
|
||||
```
|
||||
|
||||
这说明项目已经把 Koin 版本统一收在版本目录里了。
|
||||
|
||||
---
|
||||
|
||||
## 3. “如何引用”分成两层理解
|
||||
很多同学会把“引用”只理解成 `implementation(...)`,
|
||||
其实这里有两层:
|
||||
|
||||
### 第一层:Gradle 依赖引用
|
||||
也就是在构建脚本里写:
|
||||
|
||||
```kotlin
|
||||
implementation(libs.koin.core)
|
||||
implementation(libs.koin.androidx.compose)
|
||||
```
|
||||
|
||||
### 第二层:代码中的 API 引用
|
||||
也就是在 Kotlin 代码里 import 并使用,比如:
|
||||
|
||||
```kotlin
|
||||
import org.koin.androidx.compose.koinViewModel
|
||||
import org.koin.androidx.viewmodel.dsl.viewModel
|
||||
import org.koin.dsl.module
|
||||
```
|
||||
|
||||
课堂上建议把这两层都讲清楚,
|
||||
不然学生会以为“加了依赖就等于接入完成”。
|
||||
|
||||
---
|
||||
|
||||
# 三、这次最小演示要改什么
|
||||
|
||||
本次实际落地只改 4 个点:
|
||||
|
||||
1. 新增一个 `AppModule.kt`
|
||||
2. 在 `MainActivity` 启动 Koin
|
||||
3. 在 `App.kt` 里改成 `koinViewModel()`
|
||||
4. 把 `ShopViewModel` 改成构造函数注入 `ProductRepository`
|
||||
|
||||
这就是完整演示闭环。
|
||||
|
||||
---
|
||||
|
||||
# 四、Step 1:新增 Koin module
|
||||
|
||||
## 为什么要先建 module
|
||||
Koin 不是自动凭空知道要创建什么对象的。
|
||||
我们需要先告诉它:
|
||||
|
||||
- `ProductApi` 怎么创建
|
||||
- `ProductRepository` 怎么创建
|
||||
- `ShopViewModel` 怎么创建
|
||||
|
||||
这个“告诉它如何创建对象”的地方,就叫 `module`。
|
||||
|
||||
## 新增文件
|
||||
文件路径:
|
||||
`composeApp/src/androidMain/kotlin/com/example/minishop/AppModule.kt`
|
||||
|
||||
完整代码:
|
||||
|
||||
```kotlin
|
||||
package com.example.minishop
|
||||
|
||||
import com.example.minishop.network.ProductApi
|
||||
import com.example.minishop.repository.ProductRepository
|
||||
import org.koin.androidx.viewmodel.dsl.viewModel
|
||||
import org.koin.core.context.GlobalContext
|
||||
import org.koin.core.context.startKoin
|
||||
import org.koin.dsl.module
|
||||
|
||||
val appModule = module {
|
||||
single { ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false) }
|
||||
single { ProductRepository(api = get()) }
|
||||
viewModel { ShopViewModel(productRepository = get()) }
|
||||
}
|
||||
|
||||
fun initAppKoin() {
|
||||
if (GlobalContext.getOrNull() != null) return
|
||||
startKoin {
|
||||
modules(appModule)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 这一段怎么讲
|
||||
|
||||
### 1)`module { ... }` 是干什么的
|
||||
它表示:
|
||||
|
||||
> 这里统一描述“哪些对象由 Koin 管理,以及它们怎么创建”。
|
||||
|
||||
### 2)`single { ... }` 是什么意思
|
||||
`single` 表示单例。
|
||||
也就是整个容器里,这个对象只创建一份,后面重复使用。
|
||||
|
||||
这里:
|
||||
|
||||
```kotlin
|
||||
single { ProductApi(...) }
|
||||
single { ProductRepository(api = get()) }
|
||||
```
|
||||
|
||||
表示:
|
||||
- `ProductApi` 只创建一份
|
||||
- `ProductRepository` 只创建一份
|
||||
|
||||
### 3)`get()` 是什么意思
|
||||
`get()` 的意思是:
|
||||
|
||||
> 从 Koin 容器里拿一个当前需要的依赖。
|
||||
|
||||
比如:
|
||||
|
||||
```kotlin
|
||||
single { ProductRepository(api = get()) }
|
||||
```
|
||||
|
||||
表示:
|
||||
- 创建 `ProductRepository` 时,`api` 参数不手动 new
|
||||
- 而是从容器里取一个 `ProductApi`
|
||||
|
||||
### 4)`viewModel { ... }` 是什么意思
|
||||
```kotlin
|
||||
viewModel { ShopViewModel(productRepository = get()) }
|
||||
```
|
||||
|
||||
这表示:
|
||||
- `ShopViewModel` 由 Koin 按 ViewModel 的方式来管理
|
||||
- 构造它时需要一个 `ProductRepository`
|
||||
- 这个依赖同样从容器里获取
|
||||
|
||||
### 5)为什么要有 `initAppKoin()`
|
||||
因为定义了 module 还不够,
|
||||
还需要在 App 启动时真正把 Koin 启起来。
|
||||
|
||||
`initAppKoin()` 就是在做这件事。
|
||||
|
||||
### 6)为什么要判断 `GlobalContext.getOrNull()`
|
||||
这是为了避免重复初始化。
|
||||
|
||||
如果 Activity 重建或某些场景下再次触发初始化,
|
||||
直接 `startKoin()` 可能会报错。
|
||||
|
||||
所以先判断:
|
||||
- 如果已经启动过,就直接返回
|
||||
- 没启动过,才执行 `startKoin()`
|
||||
|
||||
---
|
||||
|
||||
# 五、Step 2:在 MainActivity 启动 Koin
|
||||
|
||||
## 为什么要在入口启动
|
||||
Koin 只是“定义好了规则”还不够,
|
||||
还要在应用入口把容器真正启动起来。
|
||||
|
||||
在这个项目里,最直接的入口就是 `MainActivity`。
|
||||
|
||||
## 修改文件
|
||||
文件路径:
|
||||
`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
|
||||
import com.example.minishop.db.initAppContext
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
initAppContext(applicationContext)
|
||||
initAppKoin()
|
||||
setContent {
|
||||
App()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 这一段怎么讲
|
||||
|
||||
这里要让学生知道:
|
||||
|
||||
1. `initAppContext(applicationContext)`
|
||||
- 这是原来数据库那套逻辑需要的
|
||||
- 和 Koin 是两回事
|
||||
|
||||
2. `initAppKoin()`
|
||||
- 这是本次新增
|
||||
- 作用是启动 Koin 容器
|
||||
|
||||
顺序上通常就是:
|
||||
- 先做原有基础初始化
|
||||
- 再启动 Koin
|
||||
- 最后再进入 Compose UI
|
||||
|
||||
---
|
||||
|
||||
# 六、Step 3:在 Compose 页面里从 Koin 拿 ViewModel
|
||||
|
||||
## 原来是怎么写的
|
||||
原来在 `App.kt` 里是这样:
|
||||
|
||||
```kotlin
|
||||
val vm: ShopViewModel = androidx.lifecycle.viewmodel.compose.viewModel()
|
||||
```
|
||||
|
||||
这表示使用默认方式获取 ViewModel。
|
||||
|
||||
## 现在改成什么
|
||||
我们改成:
|
||||
|
||||
```kotlin
|
||||
import org.koin.androidx.compose.koinViewModel
|
||||
|
||||
val vm: ShopViewModel = koinViewModel()
|
||||
```
|
||||
|
||||
## 修改文件
|
||||
文件路径:
|
||||
`composeApp/src/androidMain/kotlin/com/example/minishop/App.kt`
|
||||
|
||||
关键改动:
|
||||
|
||||
```kotlin
|
||||
import org.koin.androidx.compose.koinViewModel
|
||||
```
|
||||
|
||||
以及:
|
||||
|
||||
```kotlin
|
||||
val vm: ShopViewModel = koinViewModel()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 这一段怎么讲
|
||||
|
||||
### 1)`koinViewModel()` 是干什么的
|
||||
它的作用是:
|
||||
|
||||
> 在 Compose 里,向 Koin 要一个 ViewModel。
|
||||
|
||||
也就是说,页面不再自己决定怎么创建 ViewModel,
|
||||
而是交给 Koin 按我们在 module 里写好的规则来创建。
|
||||
|
||||
### 2)这就是“代码中如何引用”的一个典型例子
|
||||
除了 Gradle 里的依赖引用,
|
||||
这里也要让学生看到:
|
||||
|
||||
```kotlin
|
||||
import org.koin.androidx.compose.koinViewModel
|
||||
```
|
||||
|
||||
这是 Koin 在代码中的实际用法引用。
|
||||
|
||||
### 3)为什么这里不直接写 `ShopViewModel()`
|
||||
因为如果你直接在 UI 里 new:
|
||||
- 又绕回手动创建对象了
|
||||
- DI 就失去意义了
|
||||
|
||||
用了 `koinViewModel()` 后,UI 只负责声明“我要这个 ViewModel”,
|
||||
不再负责“怎么造出来”。
|
||||
|
||||
---
|
||||
|
||||
# 七、Step 4:把 ShopViewModel 改成构造函数注入
|
||||
|
||||
## 原来是怎么写的
|
||||
原来的写法是:
|
||||
|
||||
```kotlin
|
||||
class ShopViewModel : ViewModel() {
|
||||
private val productRepository = ProductRepository(
|
||||
api = ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false)
|
||||
)
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
这种写法的问题在于:
|
||||
- `ShopViewModel` 自己 new 了依赖
|
||||
- 依赖创建逻辑和业务逻辑混在一起
|
||||
|
||||
## 现在改成什么
|
||||
改成:
|
||||
|
||||
```kotlin
|
||||
class ShopViewModel(
|
||||
private val productRepository: ProductRepository,
|
||||
) : ViewModel()
|
||||
```
|
||||
|
||||
## 修改文件
|
||||
文件路径:
|
||||
`composeApp/src/androidMain/kotlin/com/example/minishop/ShopViewModel.kt`
|
||||
|
||||
关键改动如下:
|
||||
|
||||
```kotlin
|
||||
class ShopViewModel(
|
||||
private val productRepository: ProductRepository,
|
||||
) : ViewModel() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||
|
||||
private val database = createShopDatabase()
|
||||
private val cartRepository = CartRepository(database)
|
||||
private val orderRepository = OrderRepository(database)
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 这一段怎么讲
|
||||
|
||||
### 1)这就是构造函数注入
|
||||
意思是:
|
||||
- `ShopViewModel` 不自己 new `ProductRepository`
|
||||
- 由外部把 `ProductRepository` 传进来
|
||||
|
||||
而这个“外部”,在这里就是 Koin。
|
||||
|
||||
### 2)为什么只注入 `ProductRepository`
|
||||
因为这次我们只想做一个**最小演示切片**。
|
||||
|
||||
如果把:
|
||||
- `CartRepository`
|
||||
- `OrderRepository`
|
||||
- `ShopDatabase`
|
||||
- `DatabaseFactory`
|
||||
|
||||
全都一口气改成注入,
|
||||
课堂复杂度会一下升高。
|
||||
|
||||
所以这次刻意只改一小段:
|
||||
- 先让学生看懂依赖注入的基本形状
|
||||
- 不急着把所有对象都交给容器
|
||||
|
||||
### 3)这不是“最佳最终形态”,而是“教学上最合适的第一步”
|
||||
要明确告诉学生:
|
||||
|
||||
> 现在这版不是要证明“项目已经完整 DI 化”,
|
||||
> 而是先证明“我们已经会把一条依赖链接入 Koin”。
|
||||
|
||||
---
|
||||
|
||||
# 八、改造前后对比
|
||||
|
||||
## 改造前
|
||||
```kotlin
|
||||
class ShopViewModel : ViewModel() {
|
||||
private val productRepository = ProductRepository(
|
||||
api = ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false)
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
特点:
|
||||
- ViewModel 自己创建依赖
|
||||
- 创建逻辑写死在类内部
|
||||
- 不利于替换和测试
|
||||
|
||||
## 改造后
|
||||
```kotlin
|
||||
class ShopViewModel(
|
||||
private val productRepository: ProductRepository,
|
||||
) : ViewModel()
|
||||
```
|
||||
|
||||
配合:
|
||||
|
||||
```kotlin
|
||||
val appModule = module {
|
||||
single { ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false) }
|
||||
single { ProductRepository(api = get()) }
|
||||
viewModel { ShopViewModel(productRepository = get()) }
|
||||
}
|
||||
```
|
||||
|
||||
特点:
|
||||
- ViewModel 只声明依赖,不负责创建
|
||||
- 对象创建逻辑集中在 module
|
||||
- UI 通过 `koinViewModel()` 获取 ViewModel
|
||||
|
||||
---
|
||||
|
||||
# 九、这次改动的完整链路图
|
||||
|
||||
可以直接把这段讲给学生:
|
||||
|
||||
```text
|
||||
MainActivity
|
||||
-> initAppKoin()
|
||||
-> startKoin(modules(appModule))
|
||||
|
||||
appModule
|
||||
-> single ProductApi
|
||||
-> single ProductRepository(api = ProductApi)
|
||||
-> viewModel ShopViewModel(productRepository = ProductRepository)
|
||||
|
||||
App.kt
|
||||
-> koinViewModel<ShopViewModel>()
|
||||
|
||||
ShopViewModel
|
||||
-> 直接使用注入进来的 ProductRepository
|
||||
```
|
||||
|
||||
如果学生能看懂这张链路图,
|
||||
就说明这次最小 Koin 演示已经讲明白了。
|
||||
|
||||
---
|
||||
|
||||
# 十、课堂里一定要强调的几个点
|
||||
|
||||
## 1. Koin 不是“把所有类都塞进去”
|
||||
不要让学生误解成:
|
||||
- 只要用了 Koin,项目里所有对象都必须注入
|
||||
|
||||
不是的。
|
||||
|
||||
正确理解是:
|
||||
- 先从最适合的对象开始
|
||||
- 逐步收口对象创建逻辑
|
||||
- 一次改一条链路最稳
|
||||
|
||||
## 2. 最适合先注入的通常是这些对象
|
||||
- API Client
|
||||
- Repository
|
||||
- ViewModel
|
||||
- Service / UseCase
|
||||
|
||||
## 3. 纯工具类 / 纯函数不一定要硬塞进 Koin
|
||||
如果一个类没有状态、没有复杂构造、也没必要复用,
|
||||
那不一定非要用 DI。
|
||||
|
||||
## 4. 这次只是“演示注入”,不是“大改架构”
|
||||
这点一定要说清楚。
|
||||
不然学生会以为接 Koin 就要把项目推倒重来。
|
||||
|
||||
---
|
||||
|
||||
# 十一、如何继续扩展
|
||||
|
||||
如果后面想把这个项目继续往完整 DI 推,可以按这个顺序扩:
|
||||
|
||||
1. 注入 `ShopDatabase`
|
||||
2. 注入 `CartRepository`
|
||||
3. 注入 `OrderRepository`
|
||||
4. 再把 `DatabaseFactory` / 平台依赖也收口
|
||||
|
||||
也就是说,后续可以从:
|
||||
|
||||
```text
|
||||
ProductApi -> ProductRepository -> ShopViewModel
|
||||
```
|
||||
|
||||
继续扩成:
|
||||
|
||||
```text
|
||||
ShopDatabase -> CartRepository -> OrderRepository -> ShopViewModel
|
||||
```
|
||||
|
||||
但这已经超出这次“最小演示”的范围了。
|
||||
|
||||
---
|
||||
|
||||
# 十二、本次最小演示的验收标准
|
||||
|
||||
做到下面这几点,就说明这次 Koin 接入已经成立:
|
||||
|
||||
- [ ] 项目里新增了 `AppModule.kt`
|
||||
- [ ] `MainActivity` 启动了 `initAppKoin()`
|
||||
- [ ] `App.kt` 已经从 `viewModel()` 改成 `koinViewModel()`
|
||||
- [ ] `ShopViewModel` 已经通过构造函数接收 `ProductRepository`
|
||||
- [ ] `ProductApi` 和 `ProductRepository` 的创建逻辑已经移出 `ShopViewModel`
|
||||
|
||||
---
|
||||
|
||||
# 十三、本节小结
|
||||
|
||||
这次补充文档想讲清楚的,不是“如何把项目彻底重构成 DI 架构”,
|
||||
而是先让学生真正理解下面这句话:
|
||||
|
||||
> Koin 的核心价值,不是语法本身,
|
||||
> 而是把对象创建逻辑从业务代码里拿出来,集中管理。
|
||||
|
||||
而在这个项目里,我们已经通过最小一段改造演示了这件事:
|
||||
|
||||
- `ProductApi` 不再在 ViewModel 里手动 new
|
||||
- `ProductRepository` 不再在 ViewModel 里手动 new
|
||||
- `ShopViewModel` 通过构造函数声明依赖
|
||||
- Compose 页面通过 `koinViewModel()` 获取 ViewModel
|
||||
|
||||
这就是一个完整、可讲、也足够轻量的 Koin 入门示例。
|
||||
@@ -0,0 +1,266 @@
|
||||
# 第7节详细授课大纲
|
||||
## 主题:SQL 数据层升级 + 订单闭环 + 最小 MVI 落地
|
||||
|
||||
## 一、课程定位
|
||||
这一节不是继续堆功能,而是把第6节的商城项目做一次更接近真实业务的升级:
|
||||
|
||||
- 购物车存储:Settings → SQL
|
||||
- 业务闭环:补齐下单 → 订单列表
|
||||
- 页面状态:增加一个最小 MVI 示例
|
||||
- 错误处理:从分散 try-catch 收到统一错误结构
|
||||
|
||||
---
|
||||
|
||||
## 二、教学目标
|
||||
学生完成本节后,应该能理解并完成:
|
||||
|
||||
1. 为什么 Settings 不适合继续承载复杂业务数据
|
||||
2. SQL 在 KMP 项目里的作用是什么
|
||||
3. 如何把购物车从 Settings 升级到 SQL
|
||||
4. 最小 MVI 在 Compose 页面里如何落地
|
||||
5. 如何完成“购物车 → 下单 → 订单列表”的最小闭环
|
||||
6. 为什么错误呈现要统一收口
|
||||
|
||||
---
|
||||
|
||||
## 三、整体时间分配
|
||||
如果按 90 分钟左右来设计,可以这样分:
|
||||
|
||||
### 1. 第6节作业复盘:10 分钟
|
||||
### 2. 为什么从 Settings 升级到 SQL:10 分钟
|
||||
### 3. SQL 数据表设计与 Repository 改造:25 分钟
|
||||
### 4. 订单闭环实现:15 分钟
|
||||
### 5. 最小 MVI 落地:15 分钟
|
||||
### 6. 统一错误呈现:10 分钟
|
||||
### 7. 总结与课后作业:5 分钟
|
||||
|
||||
---
|
||||
|
||||
# 四、详细授课结构
|
||||
|
||||
## 模块1:第6节作业复盘
|
||||
### 目标
|
||||
承接上一节,顺势引出第7节为什么要升级数据层。
|
||||
|
||||
### 要讲的内容
|
||||
1. 第6节已经完成了什么
|
||||
- 商品列表网络请求
|
||||
- 购物车本地持久化
|
||||
- 基础业务闭环已经可运行
|
||||
|
||||
2. 当前实现的问题
|
||||
- Settings 本质是 key-value
|
||||
- 当业务需要查询、排序、记录历史时会越来越难维护
|
||||
- 当前购物车能存,但不适合扩展成订单体系
|
||||
|
||||
3. 引出第7节核心问题
|
||||
- 如果要继续做订单和历史记录
|
||||
- 现有存储方案就不够用了
|
||||
|
||||
### 输出结论
|
||||
> 第7节不是简单加页面,而是升级项目的数据层能力,并补齐真正的业务闭环。
|
||||
|
||||
---
|
||||
|
||||
## 模块2:为什么要从 Settings 升级到 SQL
|
||||
### 目标
|
||||
让学生明确:SQL 不是为了“更高级”,而是为了“更适合当前业务”。
|
||||
|
||||
### 要讲的内容
|
||||
|
||||
### 2.1 Settings 适合什么
|
||||
- 保存简单配置
|
||||
- 登录态、开关、轻量缓存
|
||||
- 小规模 key-value 数据
|
||||
|
||||
### 2.2 SQL 适合什么
|
||||
- 多条结构化数据
|
||||
- 增删改查
|
||||
- 排序、筛选、统计
|
||||
- 多业务对象管理
|
||||
|
||||
### 2.3 在当前商城项目里的对应场景
|
||||
- 购物车:适合放 SQL
|
||||
- 订单:更适合放 SQL
|
||||
- 后续收藏、地址、历史记录也都更适合 SQL
|
||||
- 商品列表本节仍保持网络请求,不强行扩展为缓存体系
|
||||
|
||||
### 这一部分建议落到一句话
|
||||
> Settings 解决“存一个值”,SQL 解决“管理一组业务数据”。
|
||||
|
||||
---
|
||||
|
||||
## 模块3:SQL 数据表设计 + Repository 改造
|
||||
### 目标
|
||||
让学生知道,第7节到底要建哪些表,并理解为什么 Repository 仍然是统一数据入口。
|
||||
|
||||
### 要讲的内容
|
||||
|
||||
### 3.1 购物车表设计
|
||||
建议字段:
|
||||
- productId
|
||||
- title
|
||||
- price
|
||||
- imageUrl
|
||||
- quantity
|
||||
- updatedAt
|
||||
|
||||
### 3.2 订单表设计
|
||||
建议字段:
|
||||
- orderId
|
||||
- totalPrice
|
||||
- createdAt
|
||||
- status
|
||||
|
||||
### 3.3 订单明细表设计
|
||||
建议字段:
|
||||
- id
|
||||
- orderId
|
||||
- productId
|
||||
- title
|
||||
- price
|
||||
- imageUrl
|
||||
- quantity
|
||||
|
||||
### 3.4 Repository 改造重点
|
||||
- CartRepository:从 Settings 改成 SQL
|
||||
- OrderRepository:新增创建订单 / 查询订单能力
|
||||
- UI 不关心底层是 Settings 还是 SQL
|
||||
- Repository 负责屏蔽实现细节
|
||||
|
||||
### 这一部分建议给学生的认识
|
||||
> 真正可维护的项目,不是页面直接连存储,而是页面只依赖统一的数据入口。
|
||||
|
||||
---
|
||||
|
||||
## 模块4:订单最小闭环
|
||||
### 目标
|
||||
让第7节有完整成果,而不是只停留在“换了个存储方式”。
|
||||
|
||||
### 要讲的内容
|
||||
|
||||
### 4.1 闭环流程
|
||||
- 商品加入购物车
|
||||
- 进入购物车页
|
||||
- 点击提交订单
|
||||
- 创建订单记录
|
||||
- 清空购物车
|
||||
- 打开订单列表页查看结果
|
||||
|
||||
### 4.2 这部分为什么重要
|
||||
- 证明 SQL 升级不是空转
|
||||
- 让学生看到结构化数据的业务价值
|
||||
- 为后续扩展订单状态、历史记录打基础
|
||||
|
||||
### 4.3 本节只做最小版
|
||||
不用讲:
|
||||
- 支付流程
|
||||
- 优惠券
|
||||
- 复杂订单状态流转
|
||||
|
||||
只要把下单闭环打通就够。
|
||||
|
||||
---
|
||||
|
||||
## 模块5:最小 MVI 落地
|
||||
### 目标
|
||||
只让学生理解一个页面的状态管理,不把 MVI 讲成整套沉重架构课。
|
||||
|
||||
### 要讲的内容
|
||||
|
||||
### 5.1 为什么这里引入 MVI
|
||||
不是因为 KMP 必须用 MVI,
|
||||
而是因为 Compose 页面非常适合用“单一状态源”管理界面。
|
||||
|
||||
### 5.2 只讲三个核心概念
|
||||
|
||||
#### Intent
|
||||
用户动作:
|
||||
- LoadProducts
|
||||
- Retry
|
||||
- AddToCart
|
||||
|
||||
#### State
|
||||
页面状态:
|
||||
- Loading
|
||||
- Success
|
||||
- Error
|
||||
- Empty
|
||||
|
||||
#### Reducer
|
||||
收到动作后,如何生成新的状态
|
||||
|
||||
### 5.3 为什么只改一个页面
|
||||
- 让学生理解方法,而不是淹死在重构细节里
|
||||
- 商品列表页最适合演示状态变化
|
||||
|
||||
### 这一部分结论
|
||||
> MVI 在本节只是“状态管理示范”,不是主角。
|
||||
|
||||
---
|
||||
|
||||
## 模块6:统一错误呈现
|
||||
### 目标
|
||||
让学生理解:代码不是能跑就够,错误处理也要有统一入口。
|
||||
|
||||
### 要讲的内容
|
||||
- 为什么不能每层都各自 try-catch、各自拼文案
|
||||
- 共享层统一 Success / Error 结构的好处
|
||||
- UI 层只消费标准错误对象
|
||||
- 重试按钮和错误提示应该统一出口
|
||||
|
||||
### 这一部分建议落到一句话
|
||||
> 错误处理如果到处散落,项目会越来越难维护;统一结构是工程化的起点之一。
|
||||
|
||||
---
|
||||
|
||||
## 模块7:本节总结
|
||||
### 目标
|
||||
帮助学生把第7节的核心收束成几个关键词。
|
||||
|
||||
### 总结要点
|
||||
本节做了四件事:
|
||||
|
||||
1. **数据层升级**
|
||||
- Settings 不再承担复杂业务数据
|
||||
- 购物车和订单交给 SQL
|
||||
|
||||
2. **业务闭环补齐**
|
||||
- 从购物车生成订单
|
||||
- 下单后清空购物车
|
||||
- 订单列表可查看结果
|
||||
|
||||
3. **状态管理升级**
|
||||
- 用最小 MVI 管理一个核心页面
|
||||
- 让状态变化更清晰
|
||||
|
||||
4. **错误处理收口**
|
||||
- 共享层统一错误结构
|
||||
- UI 层只负责呈现和重试
|
||||
|
||||
---
|
||||
|
||||
## 五、本节最终产出
|
||||
学生本节下课时,至少要有:
|
||||
|
||||
- SQL 版购物车
|
||||
- SQL 版订单记录
|
||||
- 一个页面完成最小 MVI 改造
|
||||
- 下单后可在订单列表看到结果
|
||||
- 错误展示和重试入口有统一收口
|
||||
|
||||
---
|
||||
|
||||
## 六、课后作业
|
||||
建议只留 2~3 个,不要太散:
|
||||
|
||||
1. 给订单增加状态字段
|
||||
- 例如:待支付 / 已完成
|
||||
|
||||
2. 增加订单筛选
|
||||
- 全部 / 待支付 / 已完成
|
||||
|
||||
3. 提交运行录屏
|
||||
- 包含加购
|
||||
- 包含下单生成订单
|
||||
- 包含订单列表展示
|
||||
@@ -13,6 +13,8 @@ kotlin = "2.2.0"
|
||||
kotlinx-serialization = "1.8.1"
|
||||
ksp = "2.2.0-2.0.2"
|
||||
ktor = "3.1.3"
|
||||
multiplatform-settings = "1.1.1"
|
||||
sqldelight = "2.2.1"
|
||||
|
||||
[libraries]
|
||||
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activityCompose" }
|
||||
@@ -31,6 +33,9 @@ ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
|
||||
ktor-client-darwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor" }
|
||||
ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" }
|
||||
ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }
|
||||
multiplatform-settings-no-arg = { module = "com.russhwolf:multiplatform-settings-no-arg", version.ref = "multiplatform-settings" }
|
||||
sqldelight-android-driver = { module = "app.cash.sqldelight:android-driver", version.ref = "sqldelight" }
|
||||
sqldelight-native-driver = { module = "app.cash.sqldelight:native-driver", version.ref = "sqldelight" }
|
||||
|
||||
[plugins]
|
||||
androidApplication = { id = "com.android.application", version.ref = "agp" }
|
||||
@@ -41,3 +46,4 @@ kmpNativeCoroutines = { id = "com.rickclephas.kmp.nativecoroutines", version.ref
|
||||
kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
|
||||
kotlinxSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
|
||||
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
|
||||
sqldelight = { id = "app.cash.sqldelight", version.ref = "sqldelight" }
|
||||
@@ -7,6 +7,7 @@ plugins {
|
||||
alias(libs.plugins.kotlinxSerialization)
|
||||
alias(libs.plugins.ksp)
|
||||
alias(libs.plugins.kmpNativeCoroutines)
|
||||
alias(libs.plugins.sqldelight)
|
||||
}
|
||||
|
||||
kotlin {
|
||||
@@ -31,14 +32,17 @@ kotlin {
|
||||
sourceSets {
|
||||
androidMain.dependencies {
|
||||
implementation(libs.ktor.client.okhttp)
|
||||
implementation(libs.sqldelight.android.driver)
|
||||
}
|
||||
iosMain.dependencies {
|
||||
implementation(libs.ktor.client.darwin)
|
||||
implementation(libs.sqldelight.native.driver)
|
||||
}
|
||||
commonMain.dependencies {
|
||||
implementation(libs.ktor.client.core)
|
||||
implementation(libs.ktor.client.content.negotiation)
|
||||
implementation(libs.ktor.serialization.kotlinx.json)
|
||||
implementation(libs.multiplatform.settings.no.arg)
|
||||
implementation(libs.koin.core)
|
||||
api(libs.kmp.observable.viewmodel)
|
||||
}
|
||||
@@ -51,6 +55,14 @@ kotlin {
|
||||
}
|
||||
}
|
||||
|
||||
sqldelight {
|
||||
databases {
|
||||
create("ShopDatabase") {
|
||||
packageName.set("com.example.minishop.db")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.example.minishop.shared"
|
||||
compileSdk = 35
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.example.minishop.db
|
||||
|
||||
import android.content.Context
|
||||
|
||||
lateinit var appContext: Context
|
||||
private set
|
||||
|
||||
fun initAppContext(context: Context) {
|
||||
appContext = context.applicationContext
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.example.minishop.db
|
||||
|
||||
import app.cash.sqldelight.db.SqlDriver
|
||||
import app.cash.sqldelight.driver.android.AndroidSqliteDriver
|
||||
|
||||
actual class DatabaseFactory actual constructor() {
|
||||
actual fun createDriver(): SqlDriver {
|
||||
return AndroidSqliteDriver(ShopDatabase.Schema, appContext, "shop.db")
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.example.minishop.network
|
||||
|
||||
import io.ktor.client.engine.HttpClientEngine
|
||||
import io.ktor.client.engine.okhttp.OkHttp
|
||||
|
||||
actual fun provideHttpEngine(): HttpClientEngine = OkHttp.create()
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.example.minishop.platform
|
||||
|
||||
actual fun platformName(): String = "Android"
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.example.minishop.platform
|
||||
|
||||
actual fun currentTimeMillis(): Long = System.currentTimeMillis()
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.example.minishop.cart
|
||||
|
||||
data class CartItem(
|
||||
val productId: String,
|
||||
val quantity: Int,
|
||||
val title: String,
|
||||
val price: Double,
|
||||
val imageUrl: String
|
||||
)
|
||||
@@ -1,17 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.example.minishop.cart
|
||||
|
||||
import com.example.minishop.db.ShopDatabase
|
||||
import com.example.minishop.model.Product
|
||||
import com.example.minishop.platform.currentTimeMillis
|
||||
|
||||
class CartRepository(
|
||||
private val database: ShopDatabase
|
||||
) {
|
||||
private val queries = database.cartQueries
|
||||
|
||||
fun items(): List<CartItem> {
|
||||
return queries.selectAll().executeAsList().map {
|
||||
CartItem(
|
||||
productId = it.product_id,
|
||||
quantity = it.quantity.toInt(),
|
||||
title = it.title,
|
||||
price = it.price,
|
||||
imageUrl = it.image_url
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun add(product: Product) {
|
||||
val current = queries.selectById(product.id).executeAsOneOrNull()
|
||||
val nextQuantity = (current?.quantity?.toInt() ?: 0) + 1
|
||||
upsert(product, nextQuantity)
|
||||
}
|
||||
|
||||
fun increase(productId: String) {
|
||||
val current = queries.selectById(productId).executeAsOneOrNull() ?: return
|
||||
queries.insertOrReplace(
|
||||
product_id = current.product_id,
|
||||
title = current.title,
|
||||
price = current.price,
|
||||
image_url = current.image_url,
|
||||
quantity = current.quantity + 1,
|
||||
updated_at = nowMillis()
|
||||
)
|
||||
}
|
||||
|
||||
fun decrease(productId: String) {
|
||||
val current = queries.selectById(productId).executeAsOneOrNull() ?: return
|
||||
val next = current.quantity.toInt() - 1
|
||||
if (next <= 0) {
|
||||
queries.deleteById(productId)
|
||||
} else {
|
||||
queries.insertOrReplace(
|
||||
product_id = current.product_id,
|
||||
title = current.title,
|
||||
price = current.price,
|
||||
image_url = current.image_url,
|
||||
quantity = next.toLong(),
|
||||
updated_at = nowMillis()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun remove(productId: String) {
|
||||
queries.deleteById(productId)
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
queries.deleteAll()
|
||||
}
|
||||
|
||||
private fun upsert(product: Product, quantity: Int) {
|
||||
queries.insertOrReplace(
|
||||
product_id = product.id,
|
||||
title = product.title,
|
||||
price = product.price,
|
||||
image_url = product.imageUrl,
|
||||
quantity = quantity.toLong(),
|
||||
updated_at = nowMillis()
|
||||
)
|
||||
}
|
||||
|
||||
private fun nowMillis(): Long = currentTimeMillis()
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.example.minishop.cart
|
||||
|
||||
@Deprecated("Lesson 7 switched cart persistence from Settings to SQLDelight")
|
||||
class CartStorage
|
||||
@@ -1,32 +0,0 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.example.minishop.checkout
|
||||
|
||||
@Deprecated("Lesson 7 moved checkout orchestration into ShopViewModel")
|
||||
class CheckoutService
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.example.minishop.db
|
||||
|
||||
import app.cash.sqldelight.db.SqlDriver
|
||||
|
||||
expect class DatabaseFactory() {
|
||||
fun createDriver(): SqlDriver
|
||||
}
|
||||
|
||||
fun createShopDatabase(factory: DatabaseFactory = DatabaseFactory()): ShopDatabase {
|
||||
return ShopDatabase(factory.createDriver())
|
||||
}
|
||||
@@ -1,8 +1,18 @@
|
||||
package com.example.minishop.model
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class Product(
|
||||
@SerialName("id")
|
||||
val id: String,
|
||||
@SerialName("title")
|
||||
val title: String,
|
||||
@SerialName("price")
|
||||
val price: Double,
|
||||
val description: String
|
||||
@SerialName("description")
|
||||
val description: String,
|
||||
@SerialName("imageUrl")
|
||||
val imageUrl: String = ""
|
||||
)
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.example.minishop.network
|
||||
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.engine.HttpClientEngine
|
||||
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.serialization.kotlinx.json.json
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
expect fun provideHttpEngine(): HttpClientEngine
|
||||
|
||||
fun createHttpClient(): HttpClient = HttpClient(provideHttpEngine()) {
|
||||
install(ContentNegotiation) {
|
||||
json(
|
||||
Json {
|
||||
ignoreUnknownKeys = true
|
||||
isLenient = true
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.example.minishop.network
|
||||
|
||||
import com.example.minishop.model.Product
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.call.body
|
||||
import io.ktor.client.request.get
|
||||
|
||||
class ProductApi(
|
||||
private val baseUrl: String,
|
||||
private val useMock: Boolean = true,
|
||||
private val client: HttpClient = createHttpClient()
|
||||
) {
|
||||
suspend fun fetchProducts(): List<Product> {
|
||||
if (useMock) return mockProducts()
|
||||
return client.get("$baseUrl/products").body()
|
||||
}
|
||||
|
||||
private fun mockProducts(): List<Product> = listOf(
|
||||
Product("1", "KMP 入门课", 99.0, "跨平台开发基础课程", "https://picsum.photos/seed/kmp1/600/360"),
|
||||
Product("2", "Compose 实战课", 149.0, "Compose 多端 UI 实战", "https://picsum.photos/seed/kmp2/600/360"),
|
||||
Product("3", "Kotlin 协程训练营", 129.0, "协程与 Flow 进阶", "https://picsum.photos/seed/kmp3/600/360"),
|
||||
Product("4", "Clean 架构速成", 199.0, "从0构建可维护架构", "https://picsum.photos/seed/kmp4/600/360"),
|
||||
Product("5", "SQLDelight 实战", 119.0, "KMP 本地数据库方案", "https://picsum.photos/seed/kmp5/600/360"),
|
||||
Product("6", "Ktor API 实战", 159.0, "跨平台网络层搭建", "https://picsum.photos/seed/kmp6/600/360")
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.example.minishop.order
|
||||
|
||||
data class OrderItem(
|
||||
val productId: String,
|
||||
val title: String,
|
||||
val price: Double,
|
||||
val imageUrl: String,
|
||||
val quantity: Int
|
||||
)
|
||||
|
||||
data class ShopOrder(
|
||||
val orderId: String,
|
||||
val totalPrice: Double,
|
||||
val status: String,
|
||||
val createdAt: Long,
|
||||
val items: List<OrderItem>
|
||||
)
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.example.minishop.order
|
||||
|
||||
import com.example.minishop.cart.CartItem
|
||||
import com.example.minishop.db.ShopDatabase
|
||||
import com.example.minishop.platform.currentTimeMillis
|
||||
import kotlin.random.Random
|
||||
|
||||
class OrderRepository(
|
||||
private val database: ShopDatabase
|
||||
) {
|
||||
private val queries = database.ordersQueries
|
||||
|
||||
fun createOrder(cartItems: List<CartItem>): ShopOrder? {
|
||||
if (cartItems.isEmpty()) return null
|
||||
|
||||
val orderId = buildOrderId()
|
||||
val createdAt = currentTimeMillis()
|
||||
val totalPrice = cartItems.sumOf { it.price * it.quantity }
|
||||
val items = cartItems.map {
|
||||
OrderItem(
|
||||
productId = it.productId,
|
||||
title = it.title,
|
||||
price = it.price,
|
||||
imageUrl = it.imageUrl,
|
||||
quantity = it.quantity
|
||||
)
|
||||
}
|
||||
|
||||
queries.insertOrder(
|
||||
order_id = orderId,
|
||||
total_price = totalPrice,
|
||||
status = "CREATED",
|
||||
created_at = createdAt
|
||||
)
|
||||
|
||||
items.forEach { item ->
|
||||
queries.insertOrderItem(
|
||||
order_id = orderId,
|
||||
product_id = item.productId,
|
||||
title = item.title,
|
||||
price = item.price,
|
||||
image_url = item.imageUrl,
|
||||
quantity = item.quantity.toLong()
|
||||
)
|
||||
}
|
||||
|
||||
return ShopOrder(
|
||||
orderId = orderId,
|
||||
totalPrice = totalPrice,
|
||||
status = "CREATED",
|
||||
createdAt = createdAt,
|
||||
items = items
|
||||
)
|
||||
}
|
||||
|
||||
fun getOrders(): List<ShopOrder> {
|
||||
return queries.selectOrders().executeAsList().map { order ->
|
||||
val items = queries.selectItemsByOrderId(order.order_id).executeAsList().map { item ->
|
||||
OrderItem(
|
||||
productId = item.product_id,
|
||||
title = item.title,
|
||||
price = item.price,
|
||||
imageUrl = item.image_url,
|
||||
quantity = item.quantity.toInt()
|
||||
)
|
||||
}
|
||||
ShopOrder(
|
||||
orderId = order.order_id,
|
||||
totalPrice = order.total_price,
|
||||
status = order.status,
|
||||
createdAt = order.created_at,
|
||||
items = items
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildOrderId(): String = "ORD-${currentTimeMillis()}-${Random.nextInt(100, 999)}"
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.example.minishop.platform
|
||||
|
||||
expect fun platformName(): String
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.example.minishop.platform
|
||||
|
||||
expect fun currentTimeMillis(): Long
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.example.minishop.repository
|
||||
|
||||
import com.example.minishop.model.Product
|
||||
import com.example.minishop.network.ProductApi
|
||||
|
||||
class ProductRepository(
|
||||
private val api: ProductApi,
|
||||
private val fallback: List<Product> = emptyList()
|
||||
) {
|
||||
suspend fun getProducts(): List<Product> {
|
||||
return runCatching { api.fetchProducts() }.getOrDefault(fallback)
|
||||
}
|
||||
|
||||
suspend fun getProductDetail(id: String): Product? {
|
||||
return getProducts().firstOrNull { it.id == id }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
CREATE TABLE cart_item (
|
||||
product_id TEXT NOT NULL PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
price REAL NOT NULL,
|
||||
image_url TEXT NOT NULL,
|
||||
quantity INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
selectAll:
|
||||
SELECT *
|
||||
FROM cart_item
|
||||
ORDER BY updated_at DESC;
|
||||
|
||||
selectById:
|
||||
SELECT *
|
||||
FROM cart_item
|
||||
WHERE product_id = ?;
|
||||
|
||||
insertOrReplace:
|
||||
INSERT OR REPLACE INTO cart_item(
|
||||
product_id,
|
||||
title,
|
||||
price,
|
||||
image_url,
|
||||
quantity,
|
||||
updated_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?);
|
||||
|
||||
deleteById:
|
||||
DELETE FROM cart_item
|
||||
WHERE product_id = ?;
|
||||
|
||||
deleteAll:
|
||||
DELETE FROM cart_item;
|
||||
@@ -0,0 +1,35 @@
|
||||
CREATE TABLE shop_order (
|
||||
order_id TEXT NOT NULL PRIMARY KEY,
|
||||
total_price REAL NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE order_item (
|
||||
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
order_id TEXT NOT NULL,
|
||||
product_id TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
price REAL NOT NULL,
|
||||
image_url TEXT NOT NULL,
|
||||
quantity INTEGER NOT NULL
|
||||
);
|
||||
|
||||
selectOrders:
|
||||
SELECT *
|
||||
FROM shop_order
|
||||
ORDER BY created_at DESC;
|
||||
|
||||
insertOrder:
|
||||
INSERT INTO shop_order(order_id, total_price, status, created_at)
|
||||
VALUES (?, ?, ?, ?);
|
||||
|
||||
insertOrderItem:
|
||||
INSERT INTO order_item(order_id, product_id, title, price, image_url, quantity)
|
||||
VALUES (?, ?, ?, ?, ?, ?);
|
||||
|
||||
selectItemsByOrderId:
|
||||
SELECT *
|
||||
FROM order_item
|
||||
WHERE order_id = ?
|
||||
ORDER BY id ASC;
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.example.minishop.db
|
||||
|
||||
import app.cash.sqldelight.db.SqlDriver
|
||||
import app.cash.sqldelight.driver.native.NativeSqliteDriver
|
||||
|
||||
actual class DatabaseFactory actual constructor() {
|
||||
actual fun createDriver(): SqlDriver {
|
||||
return NativeSqliteDriver(ShopDatabase.Schema, "shop.db")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.example.minishop.network
|
||||
|
||||
import io.ktor.client.engine.HttpClientEngine
|
||||
import io.ktor.client.engine.darwin.Darwin
|
||||
|
||||
actual fun provideHttpEngine(): HttpClientEngine = Darwin.create()
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.example.minishop.platform
|
||||
|
||||
actual fun platformName(): String = "iOS"
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.example.minishop.platform
|
||||
|
||||
import platform.Foundation.NSDate
|
||||
|
||||
actual fun currentTimeMillis(): Long = (NSDate().timeIntervalSince1970 * 1000.0).toLong()
|
||||
Reference in new issue
Block a user