【发布时间】:2019-11-30 17:44:23
【问题描述】:
我正在编写一个对 firestore 文档进行查询并在列表中返回它们的函数。如果没有文档,则返回 null(或空列表)。我对Kotlin不是很熟悉,我只知道Flutter
Kotlin 代码(我尝试过的)但它说我无法在侦听器内部返回:
fun getPlaces(type: String): List<DocumentSnapshot>? {
db.collection("users")
.whereEqualTo("type", type)
.get()
.addOnSuccessListener { documents ->
if (documents.isEmpty) {
return null
} else {
return documents
}
}
.addOnFailureListener { exception ->
Log.w(TAG, "Error getting documents: ", exception)
}
}
这是我正在尝试做的 Flutter 等价物:
List<DocumentSnapshot> getDocs(String type) async {
QuerySnapshot snaps = await db.collection('users').where('type', isEqualTo: type).getDocuments();
if (snaps.documents.isEmpty) {
return null;
} else {
return snaps.documents;
}
}
语法可能有点不对,但类似
【问题讨论】:
-
如果你想在 Kotlin 中以“正确的方式”做到这一点,以最接近你展示的飞镖的方式,你将不得不学习带有“暂停”的 Kotlin 协程函数以处理来自查询的异步响应。如果您是 Kotlin 的新手,这将需要深入了解该语言的细节以及添加到其中的 Android 平台框架。
-
那么在侦听器外部定义
var docs: List<DocumentSnapshot>? = null并将docs = documents.documents放在侦听器内部不起作用?我只需要在完成查询后将文档存储在列表中
标签: android kotlin google-cloud-firestore