从Firestore检索文档作为自定义对象

时间:2020-08-21 19:58:38

标签: kotlin google-cloud-firestore

我正在尝试从Firestore检索一个名为ShopModel的自定义对象的文档。当我调用toObject函数时,我得到以下信息 error message

我该如何解决?


ShopStore.kt

override fun getDocument(): List<ShopModel> {
        val firestore = FirebaseFirestore.getInstance()
        firestore.firestoreSettings = FirebaseFirestoreSettings.Builder().build()
        val document = firestore.collection("shops").document("1")
        document.get().addOnSuccessListener { documentSnapshot ->
            val shop = documentSnapshot.toObject<ShopModel>() //toObject 
...

ShopModel.kt

@Parcelize
data class ShopModel (
    var uuid: String?,
    var name: String?
) : Parcelable {constructor() : this("","")}

1 个答案:

答案 0 :(得分:1)

val shop = documentSnapshot.toObject<ShopModel>()更改为val shop = documentSnapshot.toObject(ShopModel::class.java)。应该可以。

您也无需指定documentSnapshot ->,而可以使用it。所以val shop = it.toObject(ShopModel::class.java)

还要确保使用Firebase-ktx代替Firebase。有一些使用kotlin扩展的手可以简化编程