by viewModels None of the following candidates is applicable because of receiver type mismatch

Viewed 549

I've tried every incantation I could find but still have a problem using by viewModel.

Here is the code in question:

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

When I manually type in "import androidx.activity.viewModels" it shows it as an "unused import directive".

My module build.gradle file looks like this:

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"

Is there something missing?

1 Answers

The by viewModels() property extension is an extension on androidx.activity.ComponentActivity, which is what provides support for ViewModels (via the ViewModelStoreOwner interface).

FlutterActivity, as per its documentation, only extends android.app.Activity and does not extend ComponentActivity. Therefore it is not possible to use by viewModels() from a FlutterActivity.

You can instead use FlutterFragmentActivity, which extends FragmentActivity (which itself extends ComponentActivity) as per this issue.

Related