You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Compose Multiplatform Precompose导航:密封类列表初始路由项返回Null

问题描述

在Compose Multiplatform应用中使用Precompose管理导航,所有屏幕通过密封类Screens的子类定义。为实现底部导航,在Screens的伴生对象中创建了导航列表navScreens,但遍历该列表时发现,作为NavHost初始路由的Profile项返回null,其余项的路由均可正常打印输出。

相关代码

screens.kt

sealed class Screens(val route: String) {
    sealed class MainNavigation(route: String, val icon: ImageVector, val label: String) : Screens(route) {
        data object Challenges : MainNavigation("challenges", Icons.Default.EventNote, "Challenges")
        data object Feed : MainNavigation("home", Icons.Default.Home, "Feed")
        // 此处缺少Leaderboard和Profile的定义
    }
    companion object {
        val navScreens: List<MainNavigation> = listOf(
            MainNavigation.Feed,
            MainNavigation.Challenges,
            MainNavigation.Leaderboard, // 引用了未定义的对象
            MainNavigation.Profile      // 引用了未定义的对象
        )
    }
}

navigation.kt

NavHost(
    modifier = Modifier.padding(bottom = paddingValues.calculateBottomPadding()),
    navigator = navigator,
    navTransition = NavTransition(),
    initialRoute = if (state.value.authState == AuthState.Authenticated) 
        Screens.MainNavigation.Profile.route else Screens.Onboarding.Landing.route
)

// 遍历导航列表的代码
Screens.navScreens.forEach { screen ->
    println("screen $screen")
}
问题分析与解决

核心问题

从提供的代码可以看出,Screens.MainNavigation内部仅定义了Challenges和Feed两个子类,而navScreens列表中却引用了未定义的Leaderboard和Profile对象。这会导致这两个元素在运行时为null,其中Profile恰好是设置的初始路由项,因此出现遍历打印为null的现象。

解决步骤

  1. 补全缺失的屏幕定义
    在Screens.MainNavigation内部添加Leaderboard和Profile的data object定义,确保每个实例都传入有效的路由、图标和标签参数:

    sealed class MainNavigation(route: String, val icon: ImageVector, val label: String) : Screens(route) {
        data object Challenges : MainNavigation("challenges", Icons.Default.EventNote, "Challenges")
        data object Feed : MainNavigation("home", Icons.Default.Home, "Feed")
        data object Leaderboard : MainNavigation("leaderboard", Icons.Default.BarChart, "Leaderboard")
        data object Profile : MainNavigation("profile", Icons.Default.Person, "Profile")
    }
    
  2. 验证导航列表的有效性
    确保navScreens列表中的所有元素都是已正确定义的MainNavigation实例,避免引用未定义的对象。

  3. 确认初始路由的正确性
    此时Screens.MainNavigation.Profile.route会指向正确的路由字符串,不会再出现null的情况,遍历navScreens时所有项都会正常打印。

内容的提问来源于stack exchange,提问作者ayitinya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 16:20:19