Skip to Content
Kotlin Multiplatform📚 Học KMPDự án KMP đầu tiên

Dự án KMP đầu tiên

Bài này hướng dẫn bạn tạo và chạy dự án Kotlin Multiplatform đầu tiên - một ứng dụng chạy được trên cả Android và iOS.

Mục tiêu

Sau bài này, bạn sẽ:

  • Tạo được dự án KMP từ wizard
  • Hiểu cấu trúc cơ bản của dự án
  • Chạy app trên Android Emulator
  • Chạy app trên iOS Simulator (macOS)

Bước 1: Tạo dự án từ Wizard

1.1. Truy cập KMP Wizard

Mở trình duyệt và truy cập: https://kmp.jetbrains.com/ 

1.2. Cấu hình dự án

  1. Project name: MyFirstKmpApp
  2. Project ID: com.example.myfirstkmpapp
  3. Platforms: Chọn ✅ Android và ✅ iOS
  4. iOS framework distribution: Chọn Regular framework
  5. Click Download

1.3. Giải nén và mở project

  1. Giải nén file .zip vừa tải
  2. Mở Android Studio
  3. File > Open → Chọn thư mục vừa giải nén
  4. Đợi Gradle sync hoàn thành (có thể mất 2-5 phút lần đầu)

Bước 2: Khám phá cấu trúc dự án

Sau khi mở project, bạn sẽ thấy cấu trúc như sau:

MyFirstKmpApp/ ├── composeApp/ # Module chứa code UI │ ├── src/ │ │ ├── commonMain/ # Code chung cho tất cả platforms │ │ │ └── kotlin/ │ │ │ └── App.kt # UI chung (Compose Multiplatform) │ │ ├── androidMain/ # Code riêng cho Android │ │ └── iosMain/ # Code riêng cho iOS │ └── build.gradle.kts ├── shared/ # Module shared logic (optional) │ └── src/ │ ├── commonMain/ # Business logic chung │ ├── androidMain/ # Logic riêng Android │ └── iosMain/ # Logic riêng iOS ├── iosApp/ # Xcode project cho iOS │ └── iosApp.xcodeproj └── build.gradle.kts # Root Gradle config

Giải thích các folder quan trọng:

FolderMô tả
commonMainCode chạy trên tất cả platforms
androidMainCode chỉ chạy trên Android
iosMainCode chỉ chạy trên iOS
composeAppModule UI dùng Compose Multiplatform
sharedModule chứa business logic dùng chung
iosAppXcode project để build iOS app

Bước 3: Xem code mẫu

File composeApp/src/commonMain/kotlin/App.kt

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

Điểm quan trọng: Đây là code Jetpack Compose thông thường, nhưng nó chạy được trên cả Android và iOS!

File shared/src/commonMain/kotlin/Greeting.kt

class Greeting { private val platform = getPlatform() fun greet(): String { return "Hello, ${platform.name}!" } }

File shared/src/commonMain/kotlin/Platform.kt

interface Platform { val name: String } expect fun getPlatform(): Platform

File shared/src/androidMain/kotlin/Platform.android.kt

class AndroidPlatform : Platform { override val name: String = "Android ${android.os.Build.VERSION.SDK_INT}" } actual fun getPlatform(): Platform = AndroidPlatform()

File shared/src/iosMain/kotlin/Platform.ios.kt

import platform.UIKit.UIDevice class IOSPlatform: Platform { override val name: String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion } actual fun getPlatform(): Platform = IOSPlatform()

Đây là pattern expect/actual - cách KMP cho phép bạn có implementation khác nhau cho từng platform!


Bước 4: Chạy trên Android

4.1. Tạo Android Emulator (nếu chưa có)

  1. Trong Android Studio, mở Device Manager (biểu tượng điện thoại bên phải)
  2. Click Create Device
  3. Chọn Pixel 7 → Click Next
  4. Chọn system image (ví dụ: API 34) → Click NextFinish
  5. Click ▶️ để start emulator

4.2. Chạy app

  1. Trên thanh toolbar, chọn configuration composeApp
  2. Chọn emulator vừa tạo
  3. Click ▶️ Run

Sau vài giây, app sẽ hiển thị trên emulator với nút “Click me!”.


Bước 5: Chạy trên iOS (macOS only)

5.1. Mở iOS Simulator

# Mở Simulator từ command line open -a Simulator

Hoặc từ Xcode: Xcode > Open Developer Tool > Simulator

5.2. Chạy từ Android Studio

  1. Trên thanh toolbar, chọn configuration iosApp
  2. Chọn iOS Simulator (ví dụ: iPhone 15)
  3. Click ▶️ Run

Lưu ý: Lần đầu build iOS có thể mất 5-10 phút.

5.3. Hoặc chạy từ Xcode

  1. Mở folder iosApp trong Finder
  2. Double-click file iosApp.xcodeproj
  3. Trong Xcode, chọn Simulator và click ▶️

Bước 6: Thử sửa code

Thay đổi greeting

Mở shared/src/commonMain/kotlin/Greeting.kt và sửa:

fun greet(): String { return "Xin chào từ ${platform.name}!" }

Hot Reload

  • Android: Click ⚡ Apply Changes hoặc rebuild
  • iOS: Rebuild project (Cmd + R trong Xcode)

Xử lý lỗi thường gặp

Lỗi: “SDK location not found”

Tạo file local.properties ở root project với nội dung: sdk.dir=/Users/yourname/Library/Android/sdk

Lỗi: Gradle sync failed

# Xóa cache và thử lại ./gradlew clean ./gradlew --refresh-dependencies

Lỗi iOS: “CocoaPods not found”

sudo gem install cocoapods cd iosApp pod install

📝 Tóm tắt

BướcAction
1Tạo project từ KMP Wizard
2Mở bằng Android Studio
3Đợi Gradle sync
4Chạy trên Android Emulator
5Chạy trên iOS Simulator
6Khám phá cấu trúc project

Tiếp theo

Học về Cấu trúc dự án KMP để hiểu sâu hơn cách tổ chức code.

Last updated on