如果我违反了一些规则,或者之前已经有人问过这个问题,我深表歉意。我花了很多时间来谷歌搜索示例,以及有关堆栈溢出和其他资源的问题。但我根本不明白如何从 firestore 集合中获取文档字段,并在 jetpack 撰写文本函数中显示字符串值。
我是编程和 Android 方面的初学者。所以我确实有一些根本性的误解,我应该如何做到这一点,但这是我的尝试,但不起作用,我不明白为什么。
在 Firestore 中,我有一个名为 users 的集合,其中包含一个名为 HolidaySavings 的文档,该文档有一个名为 name 的字符串类型字段。
我想在可组合文本函数中显示名称的值。
我有一个名为storedData 的类来处理Firestore。它具有创建和更新集合/文档/字段的方法。这有效。
但我似乎无法将文档中的字段值读取到 jetpack 可组合文本。
我可以将文档字段中的值读取到 Android studio 中的日志中。
这是我在类中处理 Firestore 数据库的函数
fun readDataTestFinal(): String{
val docRef = db.collection("users").document("holidaySavings")
var returnTest = ""
docRef.get()
.addOnSuccessListener { document ->
if (document != null) {
Log.d("Rtest", "DocumentSnapshot data: ${document.data}")
// I want to return this so I can use it in a composable text view
returnTest = document.get("name").toString()
} else {
Log.d("Rtest", "No such document")
}
}
.addOnFailureListener { exception ->
Log.d("Rfail", "get failed with ", exception)
}
return returnTest
}
在这里,我尝试将值读入 jetpack compose Text 函数。
var newStringFromStoredData by remember {
mutableStateOf(storedData().readDataTestFinal())
}
Text(
modifier = Modifier.background(color = Color.Blue),
text = newStringFromStoredData
)
当我运行应用程序时。一切都编译得很好,我从文档字段中获取了很好的值,并且可以在 Android Studio 的日志中看到它。
但是使用 newStringFromStoredData 值调用 Text 的 Compose 函数并没有显示在屏幕上?
谁能告诉我我不明白这是什么,以及如何做到这一点,以便我可以使用 firestore 文档字段并在 jetpack compose Text 函数中显示值?
最佳答案
Firebase 调用是异步的,这意味着它不会立即返回数据。这就是 API 使用回调的原因。因此,您的函数 readDataTestFinal
始终返回空字符串。
您可以使用的一种解决方案是将函数转换为挂起
函数,并使用协程作用域调用它。例如:
suspend fun readDataTestFinal(): String {
val docRef = firestore.collection("users")
.document("holidaySavings")
return suspendCoroutine { continuation ->
docRef.get()
.addOnSuccessListener { document ->
if (document != null) {
continuation.resume(document.get("name").toString())
} else {
continuation.resume("No such document")
}
}
.addOnFailureListener { exception ->
continuation.resumeWithException(exception)
}
}
}
在上面的代码中,我们正在转换 callback call to suspend function .
在可组合项中,您可以执行以下操作:
var newStringFromStoredData by remember {
mutableStateOf("")
}
Text(newStringFromStoredData)
LaunchedEffect(newStringFromStoredData) {
newStringFromStoredData =
try { readDataTestFinal() } catch(e: Exception) { "Error!" }
}
LaunchedEffect
将启动您的挂起函数并在加载后立即更新结果。
更好的选择是在 View 模型中定义此调用并从中调用此函数。但我认为这回答了你的问题,你可以稍后改进你的架构。您可以从here开始.
关于firebase - 如何在 jetpack 撰写 TextView 中显示 Firestore 集合文档中的文档字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72190704/