mcpField
K
kmp-navigation

kmp-navigation

github.com/ahmed3elshaer开发6640 次安装19 周前更新
代码仓库

关于 kmp-navigation

KMP Navigation 为 Kotlin Multiplatform 项目提供导航方案,涵盖 Voyager、Decompose 和平台原生桥接,并介绍标签页、深链、参数及状态保留。

主要功能

  1. 01Voyager 和 Decompose 导航方案
  2. 02平台原生导航桥接
  3. 03标签页导航示例
  4. 04深链方案
  5. 05类型安全的导航参数
  6. 06屏幕状态保留

适用场景

  1. 01为 KMP 项目选择导航方案
  2. 02实现标签页或深链
  3. 03在屏幕间传递类型化参数
  4. 04保留屏幕状态

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/ahmed3elshaer/everything-claude-code-mobile --skill kmp-navigation

安装后在 Claude Code 中输入/kmp-navigation确认已加载。

详细介绍

KMP 导航

适用于 Kotlin Multiplatform 的跨平台导航策略。

导航选项

1. Voyager(推荐)
// build.gradle.kts
dependencies {
    implementation("cafe.adriel.voyager:voyager-navigator:1.0.0")
    implementation("cafe.adriel.voyager:voyager-screen-model:1.0.0")
}
// commonMain/kotlin/navigation/VoyagerNavigation.kt
@Serializable
data object HomeScreen : Screen

@Serializable
data class DetailScreen(val id: String) : Screen

@Composable
fun AppNavigation() {
    Navigator(HomeScreen) { navigator ->
        VoyagerNavigation(
            navigator = navigator,
            screenModels = { rememberScreenModel { AppScreenModel() } }
        )
    }
}

@Composable
fun HomeScreen() {
    Screen { // Voyager's Screen composable
        val navigator = LocalNavigator.currentOrThrow

        Button(onClick = { navigator.push(DetailScreen("123")) }) {
            Text("Go to Detail")
        }
    }
}
2. Decompose
// build.gradle.kts
dependencies {
    implementation("com.arkivanov.decompose:decompose:2.1.0")
    implementation("com.arkivanov.decompose:extensions-compose-jetpack:2.1.0")
}
// commonMain/kotlin/navigation/DecomposeNavigation.kt
sealed class Config : Parcelable {
    @Parcelize
    data object Home : Config()

    @Parcelize
    data class Detail(val id: String) : Config()
}

@Composable
fun AppNavigation() {
    val navigator = rememberNavigator()

    Decomanavigation(
        navigator = navigator,
        initialConfiguration = Config.Home
    ) {
        when (val config = it.configuration) {
            is Config.Home -> HomeScreen(
                onNavigateToDetail = { navigator.push(Config.Detail(it)) }
            )
            is Config.Detail -> DetailScreen(
                id = config.id,
                onBack = { navigator.pop() }
            )
        }
    }
}
3. 平台原生桥接
// commonMain/kotlin/navigation/Navigator.kt
sealed class Screen : Parcelable {
    @Parcelize
    data object Home : Screen()

    @Parcelize
    data class Detail(val id: String) : Screen()
}

interface Navigator {
    val navigationStack: StateFlow<List<Screen>>
    fun navigateTo(screen: Screen)
    fun navigateBack()
}

expect class Navigator() : Navigator

// androidMain - Compose Navigation
actual class Navigator : Navigator {
    private val _stack = MutableStateFlow(listOf(Screen.Home))
    override val navigationStack: StateFlow<List<Screen>> = _stack.asStateFlow()

    @Composable
    fun SetupNavigation() {
        val navController = rememberNavController()

        NavHost(navController, startDestination = "home") {
            composable("home") {
                HomeScreen(
                    onNavigateToDetail = { navController.navigate("detail/$it") }
                )
            }
            composable("detail/{id}") { backStackEntry ->
                val id = backStackEntry.arguments?.getString("id") ?: ""
                DetailScreen(id, onBack = { navController.popBackStack() })
            }
        }
    }
}

// iosMain - SwiftUI Navigation wrapper
actual class Navigator : Navigator {
    private val _stack = MutableStateFlow(listOf(Screen.Home))
    override val navigationStack: StateFlow<List<Screen>> = _stack.asStateFlow()

    fun toSwiftUI() -> some View {
        // Bridge to SwiftUI NavigationStack
    }
}

标签导航

Voyager 标签页
// commonMain/kotlin/navigation/TabNavigation.kt
enum class Tab {
    HOME,
    SEARCH,
    PROFILE
}

@Composable
fun TabNavigation() {
    val navigator = rememberTabNavigator()

    TabNavigator(tab = navigator.current) {
        // Tab content
    }
}
Decompose 标签页
// commonMain/kotlin/navigation/Tabs.kt
enum class Tab {
    HOME,
    SEARCH,
    PROFILE
}

@Composable
fun Tabs(
    navigator: StackNavigator,
    selectedTab: MutableState<Tab>
) {
    Row {
        Tab.values().forEach { tab ->
            Button(
                onClick = { selectedTab.value = tab }
            ) {
                Text(tab.name)
            }
        }
    }
}

深层链接

// commonMain/kotlin/navigation/DeepLink.kt
sealed class Screen : Parcelable {
    @Parcelize
    data object Home : Screen()

    @Parcelize
    data class Detail(val id: String) : Screen()

    companion object {
        fun fromDeepLink(url: String): Screen? {
            return when {
                url.contains("/home") -> Home
                "/detail/([a-z0-9]+)".toRegex().find(url) != null -> {
                    val id = "/detail/([a-z0-9]+)".toRegex().find(url)!!.groupValues[1]
                    Detail(id)
                }
                else -> null
            }
        }
    }
}

导航参数

类型安全参数
// ✅ Sealed class with arguments
@Serializable
sealed class Screen : Parcelable {
    @Parcelize
    data object Home : Screen()

    @Parcelize
    data class UserDetail(
        val userId: String,
        val section: String? = null
    ) : Screen()

    @Parcelize
    data class EditItem(
        val itemId: String,
        val mode: EditMode = EditMode.View
    ) : Screen()
}

@Serializable
enum class EditMode {
    View, Edit, Create
}

状态保留

Voyager ScreenModel
class DetailScreenModel(
    private val userId: String,
    private val repository: UserRepository
) : ScreenModel {
    val user = mutableStateOf<User?>(null)
    val isLoading = mutableStateOf(false)

    init {
        loadUser()
    }

    private fun loadUser() {
        viewModelScope.launch {
            isLoading.value = true
            user.value = repository.getUser(userId)
            isLoading.value = false
        }
    }
}

@Composable
fun DetailScreen(
    userId: String,
    onBack: () -> Unit
) {
    val model = rememberScreenModel { DetailScreenModel(userId) }

    if (model.isLoading.value) {
        CircularProgressIndicator()
    } else {
        model.user.value?.let { user ->
            UserContent(user, onBack)
        }
    }
}

请记住:根据项目需求选择导航库。追求简单可选 Voyager,追求可控性可选 Decompose,需要完整支持平台功能则可选平台原生方案。

评论

支持 Markdown