Firebase Auth(Kotlin Multiplatform / AndroidMain)中的未解析引用:'await' 和 'user'

移动开发 2026-07-10

我正在一个Kotlin Multiplatform (KMP) 项目中工作,试图在 androidMain 内实现一个Firebase身份验证数据源。即使添加了Firebase依赖,编译器仍然无法解析 .await() 扩展,以及 .user 属性,在Auth Task上。

我的设置:

  • Kotlin版本:2.0.0(或你所使用的版本)
  • Gradle版本:8.x
  • 项目:Kotlin Multiplatform(Compose Multiplatform)

我的代码(FirebaseAuthDataSource.ktandroidMain 中):

Kotlin

interface AuthRemoteRepository {
    suspend fun login(email: String, password: String): Result<UserToken>
}

class FirebaseAuthDataSource(
    private val auth: FirebaseAuth
) : AuthRemoteRepository {
    override suspend fun login(email: String, password: String): Result<UserToken> {
        return try {
            val authResult = auth.signInWithEmailAndPassword(email, password)
            // Error here: Unresolved reference 'user'
            val user = authResult.user ?: throw IllegalStateException("User is null") 

            // Error here: Unresolved reference 'await'
            val tokenResult = user.getIdToken(true).await() 

            Result.success(UserToken(tokenResult.token ?: ""))
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
}

我的 build.gradle.kts(:data模块):

Kotlin

kotlin {
    androidTarget()
    sourceSets {
        val androidMain by getting {
            dependencies {
                implementation(platform("com.google.firebase:firebase-bom:33.10.0"))
                implementation("com.google.firebase:firebase-auth")
                // I tried adding this, but it still doesn't work
                implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.10.2")
            }
        }
    }
}

我尝试过的方法:

  1. 添加 import kotlinx.coroutines.tasks.await,但IDE显示它不存在。
  2. 清理并重新构建项目。
  3. 使缓存无效并重启Android Studio。
  4. 查看外部库:kotlinx-coroutines-android 存在,但在类路径中找不到 tasks.await

如何在KMP模块中正确导入Firebase Tasks的 .await() 扩展?

解决方案

你调用 await() 的那一行是完全没问题的。你在那里报错,是因为 user 变量没有被正确地定义。

不过这实际上发生在上一行,这里才是问题所在:你尝试访问 authResult.user,但这已经出现如下编译错误:

未解析的引用 'user'。

原因在于 authResult 实际上并不是 AuthResult 类型,因此你不能访问它的 user 属性。它其实是一个 Task<AuthResult>。因此,要从Task中解包AuthResult,首先需要对它调用 await()

val user = authResult.await().user

(或者简单地在上方定义 authResult 的那一行添加 await()

解决上述问题后,其余的代码应该按预期工作。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章