You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Firestore的Users集合获取当前用户文档并赋值给变量

从Firestore获取当前用户文档并全局复用

1. 优化用户ID获取逻辑

先简化原有的用户ID获取函数,用Kotlin空安全操作更简洁:

fun getCurrentUserID(): String? {
    return FirebaseAuth.getInstance().currentUser?.uid
}

这样能明确返回值可能为null的情况,避免后续隐式空指针风险。

2. 定义USER模型类

确保模型类适配Firestore的序列化规则,这里提供两种常见实现:

方式一:Kotlin序列化(推荐)

import kotlinx.serialization.Serializable

@Serializable
data class USER(
    val userId: String = "",
    val userName: String = "",
    val email: String = "",
    // 根据实际需求添加其他用户字段
)

方式二:Firebase默认序列化(兼容Java)

data class USER(
    val userId: String = "",
    val userName: String = "",
    val email: String = ""
) {
    // 必须保留无参构造函数供Firebase反射使用
    constructor() : this("", "", "")
}

3. 获取Firestore文档并赋值

调用Firestore API获取当前用户文档,解析后存入全局变量:

import android.util.Log
import com.google.firebase.firestore.FirebaseFirestore

fun fetchCurrentUser() {
    val currentUserId = getCurrentUserID() ?: return // 用户未登录则直接终止逻辑

    FirebaseFirestore.getInstance()
        .collection("Users")
        .document(currentUserId)
        .get()
        .addOnSuccessListener { doc ->
            if (doc.exists()) {
                // 将文档映射为USER对象
                val currentUser = doc.toObject(USER::class.java)
                // 存入全局管理类
                UserManager.currentUser = currentUser
            }
        }
        .addOnFailureListener { e ->
            Log.e("FirestoreError", "获取用户数据失败", e)
        }
}

4. 全局存储用户数据(供多Activity调用)

创建单例类管理全局用户实例,其他Activity可直接访问:

object UserManager {
    // 全局用户变量,初始为null
    var currentUser: USER? = null
}

在其他Activity中使用示例:

// 获取用户名,为空时显示默认值
val userName = UserManager.currentUser?.userName ?: "未知用户"

关键注意点

  • 建议在App启动页(SplashActivity)或用户登录成功后调用fetchCurrentUser(),提前加载数据。
  • 如果需要实时同步用户数据变化,可将get()替换为addSnapshotListener(),文档更新时自动同步全局变量。

内容的提问来源于stack exchange,提问作者MRane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 08:45:18