繁体   English   中英

Dagger2 可空注入

[英]Dagger2 nullable injection

我正在尝试用 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()必须返回可为空的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> {

首先,我尝试使AuthActivity中的logo var 可以为空,但 lateinit 不能为空。 如果我不使用 lateinit 并像这样制作: var logo: Drawable? = null var logo: Drawable? = null我收到关于私有字段注入的奇怪错误,即使它不是私有的:

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

我该如何解决? 谢谢。

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

您还需要标记归档的“徽标”@Nullable。

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

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

将 logo 字段设为可为空。 Dagger 不允许将可为空的 object 注入到不可为空的字段中。

 @Inject
 var logo: Drawable?=null

在 Java 中,

@Nullable
@Inject
Drawable logo;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM