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
- Project name:
MyFirstKmpApp - Project ID:
com.example.myfirstkmpapp - Platforms: Chọn ✅ Android và ✅ iOS
- iOS framework distribution: Chọn Regular framework
- Click Download
1.3. Giải nén và mở project
- Giải nén file
.zipvừa tải - Mở Android Studio
- File > Open → Chọn thư mục vừa giải nén
- Đợ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 configGiải thích các folder quan trọng:
| Folder | Mô tả |
|---|---|
commonMain | Code chạy trên tất cả platforms |
androidMain | Code chỉ chạy trên Android |
iosMain | Code chỉ chạy trên iOS |
composeApp | Module UI dùng Compose Multiplatform |
shared | Module chứa business logic dùng chung |
iosApp | Xcode 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(): PlatformFile 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ó)
- Trong Android Studio, mở Device Manager (biểu tượng điện thoại bên phải)
- Click Create Device
- Chọn Pixel 7 → Click Next
- Chọn system image (ví dụ: API 34) → Click Next → Finish
- Click ▶️ để start emulator
4.2. Chạy app
- Trên thanh toolbar, chọn configuration composeApp
- Chọn emulator vừa tạo
- 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 SimulatorHoặc từ Xcode: Xcode > Open Developer Tool > Simulator
5.2. Chạy từ Android Studio
- Trên thanh toolbar, chọn configuration iosApp
- Chọn iOS Simulator (ví dụ: iPhone 15)
- 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
- Mở folder
iosApptrong Finder - Double-click file
iosApp.xcodeproj - 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/sdkLỗi: Gradle sync failed
# Xóa cache và thử lại
./gradlew clean
./gradlew --refresh-dependenciesLỗi iOS: “CocoaPods not found”
sudo gem install cocoapods
cd iosApp
pod install📝 Tóm tắt
| Bước | Action |
|---|---|
| 1 | Tạo project từ KMP Wizard |
| 2 | Mở bằng Android Studio |
| 3 | Đợi Gradle sync |
| 4 | Chạy trên Android Emulator |
| 5 | Chạy trên iOS Simulator |
| 6 | Khá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