Skip to content

使用 Kotlin Multiplatform 建構全端應用程式

程式碼範例: full-stack-task-manager

使用的外掛程式:Routing路由是伺服器應用程式中處理傳入請求的核心外掛程式。、 kotlinx.serialization、 Content NegotiationContentNegotiation 外掛程式有兩個主要用途:在用戶端與伺服器之間協商媒體類型,以及將內容以特定格式進行序列化/反序列化。、 Compose Multiplatform、 Kotlin Multiplatform

在本文中,您將學習如何使用 Kotlin 開發可在 Android、iOS、Web 和桌面平台上執行的全端應用程式,同時利用 Ktor 實現流暢的資料處理。

在本教學結束時,您將了解如何執行以下操作:

  • 使用 Kotlin Multiplatform 建立全端應用程式。
  • 理解使用 IntelliJ IDEA 產生的專案。
  • 建立呼叫 Ktor 服務的 Compose Multiplatform 用戶端。
  • 在設計的不同層次之間重複使用共用型別。
  • 正確包含並配置多平台庫。

在先前的教學中,我們使用了任務管理器(Task Manager)範例來 處理請求透過建置任務管理器應用程式,學習在 Kotlin 中使用 Ktor 進行路由、處理請求與參數的基本概念。、 建立 RESTful API了解如何使用 Kotlin 和 Ktor 建置後端服務,其中包含一個產生 JSON 檔案的 RESTful API 範例。,以及 透過 Exposed 整合資料庫了解使用 Exposed SQL 程式庫將 Ktor 服務連接到資料庫存儲庫的過程。。 用戶端應用程式保持盡可能精簡,以便您可以專注於學習 Ktor 的基礎知識。

您將建立一個面向 Android、iOS、Web 和桌面平台的用戶端,使用 Ktor 服務來獲取要顯示的資料。在可能的情況下,您將在用戶端和伺服器之間共用資料型別,從而加快開發速度並減少潛在的錯誤。

先決條件

如同先前的文章,您將使用 IntelliJ IDEA 作為 IDE。若要安裝並配置您的環境,請參閱 Kotlin Multiplatform 快速入門 。

如果這是您第一次使用 Compose Multiplatform,我們建議您在開始本教學之前,先完成 Compose Multiplatform 入門 教學。為了降低任務的複雜度,您可以專注於單一用戶端平台。例如,如果您從未接觸過 iOS,專注於桌面或 Android 開發可能是明智的選擇。

建立新專案

不使用 Ktor 專案產生器,而是使用 IntelliJ IDEA 中的 Kotlin Multiplatform 專案精靈。 它將建立一個基礎的多平台專案,您可以為其擴充用戶端和服務。用戶端可以使用原生 UI 程式庫(例如 SwiftUI),但在本教學中,您將使用 Compose Multiplatform 為所有平台建立共用 UI。

  1. 啟動 IntelliJ IDEA。
  2. 在 IntelliJ IDEA 中,選取 File | New | Project 。
  3. 在左側面板中,選取 Kotlin Multiplatform 。
  4. 在 New Project 視窗中指定以下欄位:
    • Name : full-stack-task-manager
    • Project ID : com.example.ktor
  5. 選取 Android 、 Desktop 、 Web 以及 Server 作為目標平台。

  6. 如果您使用的是 Mac,也請選取 iOS 。請確認已勾選 Share UI 選項。 Kotlin Multiplatform 精靈設定

  7. 點擊 Create 按鈕,並等待 IDE 產生並匯入專案。

執行服務

  1. 在 IntelliJ IDEA 中,選取 ApplicationKt 运行配置。 Run & Debug 視窗
  2. 點擊 Run 按鈕 (IntelliJ IDEA 執行圖示) 以執行配置。

    在 Run 工具視窗中將開啟一個新分頁。

  3. 前往 http://0.0.0.0:8080/ 以開啟應用程式。 您應該會在瀏覽器中看到來自 Ktor 的訊息。 Ktor 伺服器瀏覽器回應

檢查專案

server 資料夾是專案中三個 Kotlin 模組之一。另外兩個是 core 和 app 。

server 模組的結構與 Ktor 專案產生器 產生的結構非常相似。 您有一個專門的建置檔來宣告外掛程式與相依性,以及一個包含建置和啟動 Ktor 服務程式碼的原始碼集:

Kotlin Multiplatform 專案中 server 資料夾的內容

如果您查看 Application.kt 檔案中的路由指令,將會看到對 sayHello() 函式的呼叫:

kotlin
fun Application.module() {
    routing {
        get("/") {
            call.respondText(sayHello("Ktor"))
        }
    }
}

sayHello() 函式定義在 core 模組中。這是您放置要在伺服器與所有不同用戶端平台之間共用的通用程式碼的地方。

開啟 app/shared/src/commonMain 模組中的 Greeting.kt 檔案,可以看到 sayHello() 函式也在那裡被使用:

kotlin
class Greeting {
    private val platform = getPlatform()

    fun greet(): String {
        return sayHello(platform.name)
    }
}

app 模組包含以下子模組:

  • androidApp、desktopApp、iosApp 和 webApp 子模組分別包含 Android、桌面、iOS 和 Web 用戶端應用程式的平台專屬程式碼。這些用戶端應用程式目前都沒有連結到 Ktor 服務。
  • shared 子模組包含您希望提供用戶端的每個平台的原始碼集。這是因為在 commonMain 中宣告的型別需要隨目標平台而變的功能。

    例如,在 Greeting 型別中,目前平台的名稱是透過平台專屬 API,借助 預期宣告與實際宣告 (expected and actual declarations) 來獲取的。

    在 shared 子模組的 commonMain 原始碼集中,getPlatform() 函式使用了 expect 關鍵字宣告:

    kotlin
    package com.example.ktor
    
    interface Platform {
        val name: String
    }
    
    expect fun getPlatform(): Platform

    接著,每個目標平台提供 getPlatform() 函式的 actual 宣告,如下所示:

    kotlin
    package com.example.ktor
    
    import platform.UIKit.UIDevice
    
    class IOSPlatform : Platform {
        override val name: String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion
    }
    
    actual fun getPlatform(): Platform = IOSPlatform()
    kotlin
    package com.example.ktor
    
    import android.os.Build
    
    class AndroidPlatform : Platform {
        override val name: String = "Android ${Build.VERSION.SDK_INT}"
    }
    
    actual fun getPlatform(): Platform = AndroidPlatform()
    kotlin
    package com.example.ktor
    
    class JVMPlatform : Platform {
        override val name: String = "Java ${System.getProperty("java.version")}"
    }
    
    actual fun getPlatform(): Platform = JVMPlatform()
    kotlin
    package com.example.ktor
    
    class WasmPlatform : Platform {
        override val name: String = "Web with Kotlin/Wasm"
    }
    
    actual fun getPlatform(): Platform = WasmPlatform()

執行用戶端應用程式

您可以透過執行該目標的运行配置來執行用戶端應用程式。若要在 iOS 模擬器上執行應用程式,請遵循以下步驟:

  1. 在 IntelliJ IDEA 中,選取 iosApp 运行配置和模擬裝置。 Run & Debug 視窗
  2. 點擊 Run 按鈕 (IntelliJ IDEA 執行圖示) 以執行配置。
  3. 當您執行 iOS 應用程式時,它在底層會透過 Xcode 進行建置,並在 iOS 模擬器中啟動。 該應用程式會顯示一個按鈕,點擊時可切換顯示圖片。 在 iOS 模擬器中執行應用程式

    首次按下該按鈕時,目前平台的詳細資訊會新增到其文字中。實現此功能的程式碼位於 app/shared/src/commonMain/kotlin/com/example/ktor/App.kt :

    kotlin
    @Composable
    @Preview
    fun App() {
        MaterialTheme {
            var showContent by remember { mutableStateOf(false) }
            Column(
                modifier = Modifier
                    .background(MaterialTheme.colorScheme.primaryContainer)
                    .safeContentPadding()
                    .fillMaxSize(),
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Button(onClick = { showContent = !showContent }) {
                    Text("Click me!")
                }
                AnimatedVisibility(showContent) {
                    val greeting = remember { Greeting().greet() }
                    Column(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalAlignment = Alignment.CenterHorizontally,
                    ) {
                        Image(painterResource(Res.drawable.compose_multiplatform), null)
                        Text("Compose: $greeting")
                    }
                }
            }
        }
    }

    這是一個可組合函式(composable function),您稍後將在本文中對其進行修改。目前最重要的是,它顯示了一個 UI,並使用了共用的 Greeting 型別,而該型別又使用了實作通用 Platform 介面的平台專屬類別。

現在您已經了解所產生專案的結構,您可以逐步新增任務管理器功能。

新增模型型別

首先,新增模型型別並確保用戶端和伺服器都能存取它們。

  1. 前往 gradle/libs.versions.toml 並定義以下 kotlinx.serialization 相依性:
    toml
    [versions]
    kotlinx-serialization-json = "1.11.0"
    
    [libraries]
    kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serialization-json" }
    
    [plugins]
    kotlinSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
  2. 前往 core/build.gradle.kts 並新增序列化外掛程式:

    kotlin
    plugins {
        //...
        alias(libs.plugins.kotlinSerialization)
    }
  3. 在同一個檔案中,為 commonMain 原始碼集新增一個新相依性:

    kotlin
    sourceSets {
        commonMain.dependencies {
            // put your Multiplatform dependencies here
            implementation(libs.kotlinx.serialization.json)
        }
        //...
    }
  4. 在 IntelliJ IDEA 中,選取 Build | Sync Project with Gradle Files 以套用更新。Gradle 匯入完成後,您應該會發現您的 Task.kt 檔案可以成功編譯。
  5. 前往 core/src/commonMain/kotlin/com/example/ktor 並建立名為 model 的新套件。
  6. 在新套件內,建立一個名為 Task.kt 的新檔案。
  7. 新增一個代表優先級的列舉和一個代表任務的類別。 Task 類別使用來自 kotlinx.serialization 程式庫的 Serializable 型別進行註解:

    kotlin
    package com.example.ktor.model
    
    import kotlinx.serialization.Serializable
    
    enum class Priority {
        Low, Medium, High, Vital
    }
    
    @Serializable
    data class Task(
        val name: String,
        val description: String,
        val priority: Priority
    )

建立伺服器

下一個階段是建立任務管理器的伺服器實作。

  1. 前往 server/src/main/kotlin/com/example/ktor 資料夾並建立名為 model 的子套件。
  2. 在此套件內,建立一個新的 TaskRepository.kt 檔案,並為存儲庫新增以下介面:

    kotlin
    package com.example.ktor.model
    
    interface TaskRepository {
        fun allTasks(): List<Task>
        fun tasksByPriority(priority: Priority): List<Task>
        fun taskByName(name: String): Task?
        fun addOrUpdateTask(task: Task)
        fun removeTask(name: String): Boolean
    }
  3. 在同一個套件中,建立一個名為 InMemoryTaskRepository.kt 的新檔案,其中包含以下類別:

    kotlin
    package com.example.ktor.model
    
    class InMemoryTaskRepository : TaskRepository {
        private var tasks = listOf(
            Task("Cleaning", "Clean the house", Priority.Low),
            Task("Gardening", "Mow the lawn", Priority.Medium),
            Task("Shopping", "Buy the groceries", Priority.High),
            Task("Painting", "Paint the fence", Priority.Low),
            Task("Cooking", "Cook the dinner", Priority.Medium),
            Task("Relaxing", "Take a walk", Priority.High),
            Task("Exercising", "Go to the gym", Priority.Low),
            Task("Learning", "Read a book", Priority.Medium),
            Task("Snoozing", "Go for a nap", Priority.High),
            Task("Socializing", "Go to a party", Priority.High)
        )
    
        override fun allTasks(): List<Task> = tasks
    
        override fun tasksByPriority(priority: Priority) = tasks.filter {
            it.priority == priority
        }
    
        override fun taskByName(name: String) = tasks.find {
            it.name.equals(name, ignoreCase = true)
        }
    
        override fun addOrUpdateTask(task: Task) {
            var notFound = true
    
            tasks = tasks.map {
                if (it.name == task.name) {
                    notFound = false
                    task
                } else {
                    it
                }
            }
            if (notFound) {
                tasks = tasks.plus(task)
            }
        }
    
        override fun removeTask(name: String): Boolean {
            val oldTasks = tasks
            tasks = tasks.filterNot { it.name == name }
            return oldTasks.size > tasks.size
        }
    }
  4. 前往 server/src/main/kotlin/.../Application.kt 並將現有程式碼替換為以下實作:

    kotlin
    package com.example.ktor
    
    import com.example.ktor.model.InMemoryTaskRepository
    import com.example.ktor.model.Priority
    import com.example.ktor.model.Task
    import io.ktor.http.*
    import io.ktor.serialization.*
    import io.ktor.serialization.kotlinx.json.*
    import io.ktor.server.application.*
    import io.ktor.server.engine.*
    import io.ktor.server.netty.*
    import io.ktor.server.plugins.contentnegotiation.*
    import io.ktor.server.plugins.cors.routing.*
    import io.ktor.server.request.*
    import io.ktor.server.response.*
    import io.ktor.server.routing.*
    
    fun main() {
        embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application::module)
            .start(wait = true)
    }
    
    fun Application.module() {
        install(ContentNegotiation) {
            json()
        }
        install(CORS) {
            allowHeader(HttpHeaders.ContentType)
            allowMethod(HttpMethod.Delete)
            // For ease of demonstration we allow any connections.
            // Don't do this in production.
            anyHost()
        }
        val repository = InMemoryTaskRepository()
    
        routing {
            route("/tasks") {
                get {
                    val tasks = repository.allTasks()
                    call.respond(tasks)
                }
                get("/byName/{taskName}") {
                    val name = call.parameters["taskName"]
                    if (name == null) {
                        call.respond(HttpStatusCode.BadRequest)
                        return@get
                    }
                    val task = repository.taskByName(name)
                    if (task == null) {
                        call.respond(HttpStatusCode.NotFound)
                        return@get
                    }
                    call.respond(task)
                }
                get("/byPriority/{priority}") {
                    val priorityAsText = call.parameters["priority"]
                    if (priorityAsText == null) {
                        call.respond(HttpStatusCode.BadRequest)
                        return@get
                    }
                    try {
                        val priority = Priority.valueOf(priorityAsText)
                        val tasks = repository.tasksByPriority(priority)
    
    
                        if (tasks.isEmpty()) {
                            call.respond(HttpStatusCode.NotFound)
                            return@get
                        }
                        call.respond(tasks)
                    } catch (ex: IllegalArgumentException) {
                        call.respond(HttpStatusCode.BadRequest)
                    }
                }
                post {
                    try {
                        val task = call.receive<Task>()
                        repository.addOrUpdateTask(task)
                        call.respond(HttpStatusCode.NoContent)
                    } catch (ex: IllegalStateException) {
                        call.respond(HttpStatusCode.BadRequest)
                    } catch (ex: JsonConvertException) {
                        call.respond(HttpStatusCode.BadRequest)
                    }
                }
                delete("/{taskName}") {
                    val name = call.parameters["taskName"]
                    if (name == null) {
                        call.respond(HttpStatusCode.BadRequest)
                        return@delete
                    }
                    if (repository.removeTask(name)) {
                        call.respond(HttpStatusCode.NoContent)
                    } else {
                        call.respond(HttpStatusCode.NotFound)
                    }
                }
            }
        }
    }

    此實作與先前教學中的非常相似,不同之處在於為了簡潔起見,現在將所有路由程式碼都放在 Application.module() 函式中。

    輸入此程式碼並新增匯入後,您會發現多個編譯器錯誤,因為程式碼使用了多個需要作為相依性包含進來的 Ktor 外掛程式,包括用於與 Web 用戶端互動的 CORS必要相依性:io.ktor:ktor-server-cors 外掛程式。

  5. 開啟 settings.gradle.kts 並匯入 Ktor 版本目錄:
    kotlin
    dependencyResolutionManagement {
        versionCatalogs {
            create("ktorLibs").from("io.ktor:ktor-version-catalog:3.6.1")
        }
    }
  6. 開啟伺服器模組建置檔( server/build.gradle.kts )並新增以下相依性:

    kotlin
    dependencies {
        //...
        implementation(ktorLibs.serialization.kotlinx.json)
        implementation(ktorLibs.server.contentNegotiation)
        implementation(ktorLibs.server.cors)
    }
  7. 再次在主選單中選取 Build | Sync Project with Gradle Files。 匯入完成後,您應該會發現 ContentNegotiation 型別和 json() 函式的匯入運作正常。
  8. 重新執行伺服器。您應該會發現可以從瀏覽器存取這些路由。
  9. 前往 和 以查看 JSON 格式的任務伺服器回應。 瀏覽器中的伺服器回應

建立用戶端

為了讓您的用戶端能夠存取伺服器,您需要引入 Ktor Client。這涉及三種類型的相依性:

  • Ktor Client 的核心功能。
  • 處理網路連線的平台專屬引擎。
  • 對內容協商與序列化的支援。
  1. 前往 app/shared/build.gradle.kts 並新增以下相依性:
    kotlin
    kotlin {
        //...
        sourceSets {
            androidMain.dependencies {
                //...
                implementation(ktorLibs.client.android)
            }
            commonMain.dependencies {
                //...
                implementation(ktorLibs.client.core)
                implementation(ktorLibs.client.contentNegotiation)
                implementation(ktorLibs.serialization.kotlinx.json)
            }
            jvmMain.dependencies {
                implementation(ktorLibs.client.cio)
            }
            iosMain.dependencies {
                implementation(ktorLibs.client.darwin)
            }
            wasmJsMain.dependencies {
                implementation(ktorLibs.client.js)
            }
        }
    }

    完成後,您可以為用戶端新增一個 TaskApi 型別,作為 Ktor Client 的輕量包裝函式。

  2. 在主選單中選取 Build | Sync Project with Gradle Files 以匯入建置檔中的變更。
  3. 前往 app/shared/src/commonMain/kotlin/com/example/ktor 並建立名為 network 的新套件。
  4. 在新套件內,建立一個新的 HttpClientManager.kt 檔案用於用戶端設定:

    kotlin
    package com.example.ktor.network
    
    import io.ktor.client.HttpClient
    import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
    import io.ktor.client.plugins.defaultRequest
    import io.ktor.serialization.kotlinx.json.json
    import kotlinx.serialization.json.Json
    
    fun createHttpClient() = HttpClient {
        install(ContentNegotiation) {
            json(Json {
                encodeDefaults = true
                isLenient = true
                coerceInputValues = true
                ignoreUnknownKeys = true
            })
        }
        defaultRequest {
            host = "1.2.3.4" // Replace with the IP address of your current machine.
            port = 8080
        }
    }

    將 1.2.3.4 替換為您目前電腦的 IP 位址。您無法從 Android 虛擬裝置或 iOS 模擬器上執行的程式碼向 0.0.0.0 或 localhost 發起呼叫。

    尋找您的 IP 位址:

    由於行動裝置模擬器無法連線至 localhost,您需要電腦的實際 IP 位址。 若要尋找您的 IP 位址,請執行以下命令之一:

    • macOS: ifconfig | grep "inet " | grep -v 127.0.0.1
    • Linux: hostname -I | awk '{print $1}'
    • Windows: ipconfig 並尋找「IPv4 位址」
  5. 在同一個 app/shared/.../network 套件中,建立一個具有以下實作的新 TaskApi.kt 檔案:

    kotlin
    package com.example.ktor.network
    
    import com.example.ktor.model.Task
    import io.ktor.client.HttpClient
    import io.ktor.client.call.body
    import io.ktor.client.request.delete
    import io.ktor.client.request.get
    import io.ktor.client.request.post
    import io.ktor.client.request.setBody
    import io.ktor.http.ContentType
    import io.ktor.http.contentType
    
    class TaskApi(private val httpClient: HttpClient) {
    
        suspend fun getAllTasks(): List<Task> {
            return httpClient.get("tasks").body()
        }
    
        suspend fun removeTask(task: Task) {
            httpClient.delete("tasks/${task.name}")
        }
    
        suspend fun updateTask(task: Task) {
            httpClient.post("tasks") {
                contentType(ContentType.Application.Json)
                setBody(task)
            }
        }
    }
  6. 前往 app/shared/.../App.kt 並將程式碼替換為以下實作。 這將使用 TaskApi 型別從伺服器檢索任務清單,然後在一個直欄中顯示每個任務的名稱:

    kotlin
    package com.example.ktor
    
    import com.example.ktor.network.TaskApi
    import com.example.ktor.network.createHttpClient
    import com.example.ktor.model.Task
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.safeContentPadding
    import androidx.compose.material3.Button
    import androidx.compose.material3.MaterialTheme
    import androidx.compose.material3.Text
    import androidx.compose.runtime.*
    import androidx.compose.ui.Alignment
    import androidx.compose.ui.Modifier
    import kotlinx.coroutines.launch
    
    @Composable
    fun App() {
        MaterialTheme {
            val httpClient = createHttpClient()
            val taskApi = remember { TaskApi(httpClient) }
            val tasks = remember { mutableStateOf(emptyList<Task>()) }
            val scope = rememberCoroutineScope()
    
            Column(
                modifier = Modifier
                    .safeContentPadding()
                    .fillMaxSize(),
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Button(onClick = {
                    scope.launch {
                        tasks.value = taskApi.getAllTasks()
                    }
                }) {
                    Text("Fetch Tasks")
                }
                for (task in tasks.value) {
                    Text(task.name)
                }
            }
        }
    }
  7. 在伺服器執行的同時,透過執行 iosApp 运行配置來測試 iOS 應用程式。

  8. 點擊 Fetch Tasks 按鈕以顯示任務清單: 在 iOS 上執行的應用程式

    在此展示中,為了清晰起見,我們簡化了流程。在實際應用程式中,避免透過網路傳送未加密的資料至關重要。
  9. 在 Android 平台上,您需要明確授予應用程式網路權限,並允許其以明文傳送和接收資料。若要啟用這些權限,請開啟 app/androidApp/src/main/AndroidManifest.xml 並新增以下設定:

    xml
    <manifest>
        ...
        <application
                android:usesCleartextTraffic="true">
        ...
        ...
        </application>
        <uses-permission android:name="android.permission.INTERNET"/>
    </manifest>
  10. 使用 app.androidApp 运行配置執行 Android 應用程式。 您現在應該會發現您的 Android 用戶端也可以執行了: 在 Android 上執行的應用程式

  11. 對於桌面用戶端,您將為其所在的視窗指定尺寸和標題。 開啟檔案 app/desktopApp/src/.../main.kt 並透過變更 title 與設定 state 屬性來修改程式碼:

    kotlin
    package com.example.ktor
    
    import androidx.compose.ui.unit.DpSize
    import androidx.compose.ui.unit.dp
    import androidx.compose.ui.window.Window
    import androidx.compose.ui.window.WindowPosition
    import androidx.compose.ui.window.WindowState
    import androidx.compose.ui.window.application
    
    fun main() = application {
        val state = WindowState(
            size = DpSize(400.dp, 600.dp),
            position = WindowPosition(200.dp, 100.dp)
        )
        Window(
            title = "Task Manager (Desktop)",
            state = state,
            onCloseRequest = ::exitApplication,
        ) {
            App()
        }
    }
  12. 使用 app [hot] 🔥 运行配置執行桌面應用程式: 在桌面上執行的應用程式

  13. 使用以下运行配置之一執行 Web 用戶端:

    • app [js]:執行您的 Kotlin/JS 應用程式。
    • app [wasmJs]:執行您的 Kotlin/Wasm 應用程式。
    在 Web 上執行的應用程式

改進 UI

用戶端現在正在與伺服器進行通訊,但這 UI 談不上美觀。

  1. 開啟位於 app/shared/src/commonMain/.../ktor 中的 App.kt 檔案,並將現有的 App 替換為以下 App 和 TaskCard 可組合項:

    fun App() { {...}
    kotlin
    package com.example.ktor
    
    import com.example.ktor.network.TaskApi
    import com.example.ktor.model.Priority
    import com.example.ktor.model.Task
    import androidx.compose.foundation.layout.Column
    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.padding
    import androidx.compose.foundation.layout.safeContentPadding
    import androidx.compose.foundation.layout.width
    import androidx.compose.foundation.lazy.LazyColumn
    import androidx.compose.foundation.lazy.items
    import androidx.compose.foundation.shape.CornerSize
    import androidx.compose.foundation.shape.RoundedCornerShape
    import androidx.compose.material3.Card
    import androidx.compose.material3.MaterialTheme
    import androidx.compose.material3.OutlinedButton
    import androidx.compose.material3.Text
    import androidx.compose.runtime.*
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.text.font.FontWeight
    import androidx.compose.ui.unit.dp
    import androidx.compose.ui.unit.sp
    import com.example.ktor.network.createHttpClient
    import kotlinx.coroutines.launch
    
    @Composable
    fun App() {
        MaterialTheme {
            val httpClient = createHttpClient()
            val taskApi = remember { TaskApi(httpClient) }
            var tasks by remember { mutableStateOf(emptyList<Task>()) }
            val scope = rememberCoroutineScope()
    
            LaunchedEffect(Unit) {
                tasks = taskApi.getAllTasks()
            }
    
            LazyColumn(
                modifier = Modifier
                    .safeContentPadding()
                    .fillMaxSize()
            ) {
                items(tasks) { task ->
                    TaskCard(
                        task,
                        onDelete = {
                            scope.launch {
                                taskApi.removeTask(it)
                                tasks = taskApi.getAllTasks()
                            }
                        },
                        onUpdate = {
                        }
                    )
                }
            }
        }
    }
    
    @Composable
    fun TaskCard(
        task: Task,
        onDelete: (Task) -> Unit,
        onUpdate: (Task) -> Unit
    ) {
        fun pickWeight(priority: Priority) = when (priority) {
            Priority.Low -> FontWeight.SemiBold
            Priority.Medium -> FontWeight.Bold
            Priority.High, Priority.Vital -> FontWeight.ExtraBold
        }
    
        Card(
            modifier = Modifier.fillMaxWidth().padding(4.dp),
            shape = RoundedCornerShape(CornerSize(4.dp))
        ) {
            Column(modifier = Modifier.padding(10.dp)) {
                Text(
                    "${task.name}: ${task.description}",
                    fontSize = 20.sp,
                    fontWeight = pickWeight(task.priority)
                )
    
                Row {
                    OutlinedButton(onClick = { onDelete(task) }) {
                        Text("Delete")
                    }
                    Spacer(Modifier.width(8.dp))
                    OutlinedButton(onClick = { onUpdate(task) }) {
                        Text("Update")
                    }
                }
            }
        }
    }

    透過此實作,您的用戶端現在具備了一些基本功能。

    透過使用 LaunchedEffect 型別,所有任務都會在啟動時載入,而 LazyColumn 可組合項則允許使用者捲動瀏覽任務。

    最後,建立了一個單獨的 TaskCard 可組合項,它轉而使用 Card 來顯示每個 Task 的詳細資訊。並且已新增了刪除和更新任務的按鈕。

  2. 重新執行用戶端應用程式 — 例如 Android 應用程式。 您現在可以捲動瀏覽任務、檢視其詳細資訊,並刪除它們: 在 Android 上執行且具備改進 UI 的應用程式

新增更新功能

為了完善用戶端,納入允許更新任務詳細資訊的功能。

  1. 前往 app/shared/src/commonMain/.../ktor 中的 App.kt 檔案。
  2. 新增 UpdateTaskDialog 可組合項和必要的匯入,如下所示:

    kotlin
    import androidx.compose.material3.TextField
    import androidx.compose.material3.TextFieldDefaults
    import androidx.compose.ui.graphics.Color
    import androidx.compose.ui.window.Dialog
    
    @Composable
    fun UpdateTaskDialog(
        task: Task,
        onConfirm: (Task) -> Unit
    ) {
        var description by remember { mutableStateOf(task.description) }
        var priorityText by remember { mutableStateOf(task.priority.toString()) }
        val colors = TextFieldDefaults.colors(
            focusedTextColor = Color.Blue,
            focusedContainerColor = Color.White,
        )
    
        Dialog(onDismissRequest = {}) {
            Card(
                modifier = Modifier.fillMaxWidth().padding(4.dp),
                shape = RoundedCornerShape(CornerSize(4.dp))
            ) {
                Column(modifier = Modifier.padding(10.dp)) {
                    Text("Update ${task.name}", fontSize = 20.sp)
                    TextField(
                        value = description,
                        onValueChange = { description = it },
                        label = { Text("Description") },
                        colors = colors
                    )
                    TextField(
                        value = priorityText,
                        onValueChange = { priorityText = it },
                        label = { Text("Priority") },
                        colors = colors
                    )
                    OutlinedButton(onClick = {
                        val newTask = Task(
                            task.name,
                            description,
                            try {
                                Priority.valueOf(priorityText)
                            } catch (e: IllegalArgumentException) {
                                Priority.Low
                            }
                        )
                        onConfirm(newTask)
                    }) {
                        Text("Update")
                    }
                }
            }
        }
    }

    這是一個透過對話方塊顯示 Task 詳細資訊的可組合項。description 和 priority 放置在 TextField 可組合項內,以便可以進行更新。當使用者按下更新按鈕時,會觸發 onConfirm() 回呼。

  3. 更新同一個檔案中的 App 可組合項:

    kotlin
    @Composable
    fun App() {
        MaterialTheme {
            val httpClient = createHttpClient()
            val taskApi = remember { TaskApi(httpClient) }
            var tasks by remember { mutableStateOf(emptyList<Task>()) }
            val scope = rememberCoroutineScope()
            var currentTask by remember { mutableStateOf<Task?>(null) }
    
            LaunchedEffect(Unit) {
                tasks = taskApi.getAllTasks()
            }
    
            if (currentTask != null) {
                UpdateTaskDialog(
                    currentTask!!,
                    onConfirm = {
                        scope.launch {
                            taskApi.updateTask(it)
                            tasks = taskApi.getAllTasks()
                        }
                        currentTask = null
                    }
                )
            }
    
            LazyColumn(modifier = Modifier
                .safeContentPadding()
                .fillMaxSize()
            ) {
                items(tasks) { task ->
                    TaskCard(
                        task,
                        onDelete = {
                            scope.launch {
                                taskApi.removeTask(it)
                                tasks = taskApi.getAllTasks()
                            }
                        },
                        onUpdate = {
                            currentTask = task
                        }
                    )
                }
            }
        }
    }

    您正在儲存額外的狀態,即目前選取的任務。如果此值不為 null,則我們會叫用 UpdateTaskDialog 可組合項,並將 onConfirm() 回呼設定為使用 TaskApi 向伺服器發送 POST 請求。

    最後,在建立 TaskCard 可組合項時,您使用 onUpdate() 回呼來設定 currentTask 狀態變數。

  4. 重新執行用戶端應用程式。您現在應該可以使用按鈕更新每個任務的詳細資訊了。 在 Android 上刪除任務

後續步驟

在本文中,您已在 Kotlin Multiplatform 應用程式的環境中使用了 Ktor。您現在可以建立包含多個服務和用戶端的專案,面向各種不同的平台。

如您所見,在建構功能時完全可以避免任何程式碼重複或冗餘。專案所有層次中所需的型別都可以放置在 core 多平台模組中。僅服務需要的功能放在 server 模組中,而僅用戶端需要的功能則放置在 app 模組中。

這種開發方式無疑需要同時具備用戶端與伺服器端技術的相關知識。但您可以使用 Kotlin Multiplatform 庫和 Compose Multiplatform 來盡可能減少需要學習的新內容。即使您最初的重點僅在單一平台上,隨著對應用程式需求的增長,您也可以輕鬆新增其他平台。