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

Android中Hilt注入ViewModel提示需唯一@Inject构造函数如何解决

错误原因

  • 触发报错的核心是违反Hilt的ViewModel注入规则:@HiltViewModel 注解的类必须恰好有1个被@Inject修饰的构造函数,且ViewModel的所有依赖必须通过该构造函数注入,不支持在ViewModel内部使用@Inject字段注入的写法。你当前同时给构造函数和类内部的userProfile属性加了@Inject注解,导致Hilt编译时识别注入点异常,抛出对应错误。
  • 额外注意:你贴出的ViewModel代码未继承AndroidX的ViewModel基类,也可能触发Hilt的编译校验错误。

解决方案

直接将UserProfileMemorySource依赖移入ViewModel的构造函数注入即可,修改后的代码如下:

@HiltViewModel
class AccountProfileViewModel @Inject constructor(
    val userProfile: UserProfileMemorySource
) : ViewModel() {
    // 内部可直接调用userProfile的读写方法操作内存数据
}

功能说明

你现有UserProfileMemorySource的注解配置是正确的,单例注解可以保证整个App生命周期内只生成一个实例,存在里面的用户资料会一直保存在内存中,直到进程被杀或者主动调用invalidate()方法清除,完全符合你内存存储用户数据的需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:45:08