修改專案
本教學課程使用 IntelliJ IDEA,但您也可以在 Android Studio 中進行,這兩種 IDE 都擁有相同的核心功能和 Kotlin Multiplatform 支援。
這是「使用共用邏輯和 UI 建立 Compose Multiplatform 應用程式」教學課程的第三部分。在繼續之前,請確保您已完成先前的步驟。
讓我們修改由 Kotlin Multiplatform 精靈產生的程式碼,並在 App
composable 中顯示當前日期。為此,您將為專案添加新的依賴項、增強使用者介面,並在每個平台上重新執行應用程式。
添加新的依賴項
您可以使用平台特定的函式庫和預期與實際宣告來擷取日期。但我們建議您僅在沒有可用的 Kotlin Multiplatform 函式庫時才使用此方法。在這種情況下,您可以依賴 kotlinx-datetime 函式庫。
您可以在 klibs.io 上探索適用於您目標平台的 Kotlin Multiplatform 函式庫,這是 JetBrains 用於發現多平台函式庫的實驗性搜尋服務。
要使用 kotlinx-datetime
函式庫:
開啟
composeApp/build.gradle.kts
檔案,並將其添加為專案的依賴項。kotlinkotlin { // ... sourceSets { // ... commonMain.dependencies { // ... implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.2") } wasmJsMain.dependencies { implementation(npm("@js-joda/timezone", "2.22.0")) } } }
- 主要依賴項被添加到了配置通用程式碼原始碼集的區段。
- 為求簡潔,版本號直接包含在內,而不是添加到版本目錄。
- 為了在網路目標中支援時區,必要的 npm 套件參考已包含在
wasmJsMain
依賴項中。
添加依賴項後,系統會提示您重新同步專案。點擊 Sync Gradle Changes 按鈕以同步 Gradle 檔案:
在 Terminal 工具視窗中,執行以下指令:
shell./gradlew kotlinUpgradeYarnLock
此 Gradle 任務確保
yarn.lock
檔案與最新的依賴項版本同步。
增強使用者介面
開啟
composeApp/src/commonMain/kotlin/App.kt
檔案,並添加以下函數,該函數會回傳一個包含當前日期的字串:kotlinfun todaysDate(): String { fun LocalDateTime.format() = toString().substringBefore('T') val now = Clock.System.now() val zone = TimeZone.currentSystemDefault() return now.toLocalDateTime(zone).format() }
在同一個檔案中,修改
App()
composable 以包含呼叫此函數並顯示結果的Text()
composable:kotlin@Composable @Preview fun App() { MaterialTheme { var showContent by remember { mutableStateOf(false) } val greeting = remember { Greeting().greet() } Column( modifier = Modifier .safeContentPadding() .fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = "Today's date is ${todaysDate()}", modifier = Modifier.padding(20.dp), fontSize = 24.sp, textAlign = TextAlign.Center ) Button(onClick = { showContent = !showContent }) { Text("Click me!") } AnimatedVisibility(showContent) { Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { Image(painterResource(Res.drawable.compose_multiplatform), null) Text("Compose: $greeting") } } } } }
按照 IDE 的建議匯入遺失的依賴項。確保從
kotlinx.datetime
套件匯入todaysDate()
函數的所有遺失依賴項,而不是kotlin.time
。將網路應用程式從使用
Element
作為容器切換為使用帶有外部指定id
的 HTML 元素:在
composeApp/src/wasmJsMain/resources/index.html
檔案中,在<body>
內添加一個命名的元素:html<body> <div id="composeApplication" style="width:400px; height: 600px;"></div> </body>
在
composeApp/src/wasmJsMain/kotlin/main.kt
檔案中,將ComposeViewport
呼叫變更為String
變體,指向您在 HTML 檔案中指定的 ID:kotlin@OptIn(ExperimentalComposeUiApi::class) fun main() { ComposeViewport(viewportContainerId = "composeApplication") { App() } }
重新執行應用程式
您現在可以使用相同的執行設定在 Android、iOS、桌面和網路平台上重新執行應用程式:



下一步
在本教學課程的下一部分中,您將學習新的 Compose Multiplatform 概念並從頭開始建立您自己的應用程式。
取得協助
- Kotlin Slack。取得邀請並加入 #multiplatform 頻道。
- Kotlin 問題追蹤器。回報新的問題。