Dagger2 可空注入

问题描述 投票:0回答:4

我正在尝试用 Dagger 注入 Glide。

所以我有AppModule:

@Module
class AppModule {

    @Provides
    fun provideRequestOptions(): RequestOptions {
        return RequestOptions()
            .placeholder(R.drawable.white_background)
            .error(R.drawable.white_background)
    }

    @Provides
    fun provideGlideInstance(application: Application, requestOptions: RequestOptions): RequestManager{
        return Glide.with(application).setDefaultRequestOptions(requestOptions)
    }

    @Nullable
    @Provides
    fun provideAppDrawable(application: Application): Drawable? {
        return ContextCompat.getDrawable(application, R.drawable.logo)
    }
}

和 AuthActivity:

class AuthActivity : DaggerAppCompatActivity() {
    lateinit var binding: ActivityAuthBinding
    @Inject
    lateinit var logo: Drawable
    @Inject
    lateinit var requestManager: RequestManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityAuthBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setLogo()
        }

    private fun setLogo() {
        requestManager.load(logo).into(binding.loginLogo)
    }
}
AppModule 中的

provideAppDrawable()
必须返回可为 null 的
Drawable?
。当我尝试构建应用程序时,Dagger 抱怨它的可为空性:

\AppComponent.java:7: error: [Dagger/Nullable] android.graphics.drawable.Drawable is not nullable, but is being provided by @org.jetbrains.annotations.Nullable @androidx.annotation.Nullable @Provides android.graphics.drawable.Drawable com.example.daggercodingwithmitch.di.AppModule.provideAppDrawable(android.app.Application)
public abstract interface AppComponent extends dagger.android.AndroidInjector<com.example.daggercodingwithmitch.BaseApplication> {

首先我尝试使

logo
中的
AuthActivity
var 可以为空,但是 Lateinit 不能为空。如果我不使用 Lateinit 并进行如下操作:
var logo: Drawable? = null
我会收到关于私有字段注入的奇怪错误,即使它不是私有的:

\AuthActivity.java:10: error: Dagger does not support injection into private fields
    private android.graphics.drawable.Drawable logo;

我该如何修复它?谢谢。

android kotlin dagger-2
4个回答
1
投票

使徽标字段可为空。 Dagger 不允许将可为空的对象注入到不可为空的字段中。

 @Inject
 var logo: Drawable?=null

在爪哇,

@Nullable
@Inject
Drawable logo;

1
投票

您还需要将“logo”字段标记为@Nullable。

如果@Provides方法被标记为@Nullable,Dagger将只允许注入到被标记为@Nullable的站点。尝试将 @Nullable 提供与非 @Nullable 注入站点配对的组件将无法编译。

https://dagger.dev/api/2.28/dagger/Provides.html


0
投票

最简单的方法是让provideAppDrawable返回一个Drawable而不是一个Drawable?并从中删除@Nullable。是否有任何情况下返回 null 这不是一个错误?如果不是,它不应该是可为空的变量。


0
投票

Kotlin 公开属性方法(get/set)而不是字段,并隐藏底层字段。您需要使用

@JvmField
向 Dagger 公开非
lateinit
属性,Dagger 需要访问底层字段。

@Inject
@JvmField
var logo: Drawable? = null
© www.soinside.com 2019 - 2024. All rights reserved.