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

Jetpack Compose导航中hiltViewModel找不到构造函数问题排查

解决嵌套导航图中Hilt ViewModel初始化异常的方案

1. 替换为Hilt兼容的导航控制器

将普通的rememberNavController()替换为Hilt提供的扩展方法,确保导航组件能正确识别Hilt的ViewModel作用域:

val navController = rememberHiltNavController()

2. 显式指定ViewModel的导航图作用域

在ScreenC中获取ViewModel时,绑定到new导航图的BackStackEntry,避免作用域匹配错误:

val navBackStackEntry = navController.getBackStackEntry("new")
val viewModel = hiltViewModel<ScreenCViewModel>(navBackStackEntry)

3. 确认ViewModel构造函数的注解配置

检查ScreenCViewModel的构造函数是否添加了@Inject注解——这是@HiltViewModel生效的必要条件,同时确保所有依赖项已通过@Provides或@Binds完成Hilt配置:

@HiltViewModel
class ScreenCViewModel @Inject constructor(
    private val yourDependency: YourDependency
) : ViewModel() {
    // 业务逻辑代码
}

4. 排查路由命名冲突

确保所有导航路由(嵌套导航图的route、可组合项的route)无重名,避免导航时的作用域混淆问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 06:26:25