【问题标题】:by viewModels None of the following candidates is applicable because of receiver type mismatch由 viewModels 由于接收器类型不匹配,以下候选均不适用
【发布时间】:2021-02-02 21:53:40
【问题描述】:

我已经尝试了所有能找到的咒语,但 viewModel 使用仍然存在问题。

这里是有问题的代码:

class MainActivity: FlutterActivity(), OnSneakerClickListener, OnSneakerDismissListener {
private val httpclient = OkHttpClient()
val stripe = Stripe(this, "pk_test_yadayadayada")
private val viewModel: StripeIntentViewModel by viewModels() //<--dragons be here

当我手动输入“import androidx.activity.viewModels”时,它显示为“未使用的导入指令”。

我的模块 build.gradle 文件如下所示:

plugins {
id 'com.android.application'
id 'kotlin-android'
id 'checkstyle'
id 'org.jetbrains.kotlin.plugin.parcelize'
 }
 ...
 compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
    jvmTarget = "1.8"
}
...
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$androidLifecycleVersion"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$androidLifecycleVersion"
implementation "com.google.android.material:material:$materialVersion"
implementation "androidx.fragment:fragment-ktx:$fragmentVersion"
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'

implementation "androidx.activity:activity-ktx:1.1.0"
implementation "androidx.fragment:fragment-ktx:1.2.5"
implementation "android.arch.lifecycle:extensions:1.1.1"
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"

implementation "androidx.activity:activity-ktx:1.2.0-rc01"

有什么遗漏吗?

【问题讨论】:

    标签: android kotlin android-viewmodel


    【解决方案1】:

    by viewModels() property extensionandroidx.activity.ComponentActivity 的扩展,它提供对 ViewModel 的支持(通过 ViewModelStoreOwner 接口)。

    FlutterActivity,根据其documentation,仅扩展android.app.Activity,不扩展ComponentActivity。因此,不能从FlutterActivity 使用by viewModels()

    您可以改用FlutterFragmentActivity,它根据this issue 扩展FragmentActivity(它本身扩展ComponentActivity)。

    【讨论】:

    • 谢谢!我怀疑它可能与 Flutter 有关。我采用了“旧方法”: private val model: StripeIntentViewModel = ViewModelProvider(instance).get(StripeIntentViewModel::class.java) 但可能会转换为这个。
    猜你喜欢
    • 2021-09-27
    • 2021-05-11
    • 1970-01-01
    • 2020-10-18
    • 2019-04-19
    • 2022-06-12
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多