【问题标题】:lateinit property navigationManager has not been initialized in multimodule compose app using Hilt未使用 Hilt 在多模块撰写应用程序中初始化 lateinit 属性 navigationManager
【发布时间】:2021-06-25 00:13:05
【问题描述】:

App模块中的NavigationManager没有被Hilt初始化

kotlin.UninitializedPropertyAccessException:lateinit 属性 navigationManager 尚未初始化

AppModule 中provideNavigationManager() 旁边的导航图指向MainActivity 中的NavigationManager lateinit var。 当我在 app 模块中创建一个 TestObject 并在 AppModule 中提供它时,我得到了同样的错误,所以我不认为这是一个多模块问题。

 @AndroidEntryPoint
 class MainActivity : ComponentActivity() {

@Inject lateinit var navigationManager: NavigationManager

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContent {
        ChopieTheme {
            val navController = rememberNavController()
            navigationManager.commands.collectAsState().value.also { command ->
            ...
     }

:项目分级

 dependencies {
    classpath("com.android.tools.build:gradle:7.1.0-alpha02")
    classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.10")
    classpath("com.google.dagger:hilt-android-gradle-plugin:2.37")
 }

:应用程序

 dependencies {
    implementation(project(":core"))
    implementation(project(":navigation"))
 ...
 }


@HiltAndroidApp
class ChopieApp : Application() {}


@InstallIn(SingletonComponent::class)
@Module
object AppModule {

   @Singleton
   @Provides
   fun provideApplication(@ApplicationContext app: Context): ChopieApp {
      return app as ChopieApp
   }

  @Singleton
  @Provides
  fun provideNavigationManager() = NavigationManager()
}

:core(库模块)

 plugins {
   id("com.android.library")
   id("kotlin-android")
   kotlin("kapt")
   id("dagger.hilt.android.plugin")
 }
...
dependencies {
// DI
api("com.google.dagger:hilt-android:2.35")
kapt("com.google.dagger:hilt-android-compiler:2.37")
api("androidx.hilt:hilt-navigation-compose:1.0.0-alpha03")
...
}

:导航(库模块)

 dependencies {
   implementation(project(":core"))
 ...
 }

class NavigationManager {
...
}

【问题讨论】:

  • 多模块在这里应该不是问题。您可以尝试清洁并再次构建。此外,这个字段注入应该在编译时在 dagger hilt 中解决。它不应该在运行时显示错误
  • 清理/重建没有帮助。也许这是一个 kapt 问题。如果我去构建/生成/源,没有 kapt,它应该与匕首生成的文件一起存在,包括 BaseApplication_hiltComponents 类,而后者又应该包括所有组件模块。目前,Hilt 依赖项位于 :core 模块中,暴露给所有其他模块。我添加了 kotlin("kapt") 和/或 id("kotlin-kapt") 插件,但似乎都没有解决这个问题。

标签: android dagger-hilt


【解决方案1】:

我已经在两步过程中解决了这个问题:

  1. 我更改了 dagger:hilt-android 版本以匹配 kapt hilt-android-compiler 版本。
  2. 我从 :core 模块中删除了 dagger.hilt 插件和所有 hilt 依赖项,然后将它们添加到 :app 和 :navigation 模块中(api 已更改为 implementation)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多