google-cloud-firestore - SwiftUI:如何在第二个视图中从 Firestore 检索数据?
问题描述
这是我的第一个 SwiftUI 项目,在编程方面非常新。
我的内容视图有一个视图模型和一个选择器,设法将 $selection 发送到详细视图,但不知道如何让它再次从 Firestore 中读取。我有点觉得缺少了什么,就像我需要使用 if-else,但无法准确指出问题所在。在这里搜索论坛,但似乎找不到解决方案。
这是虚拟机
import Foundation
import Firebase
class FoodViewModel: ObservableObject {
@Published var datas = [Food]()
private var db = Firestore.firestore()
func fetchData(){
db.collection("meals").addSnapshotListener { (snap, err) in
DispatchQueue.main.async {
if err != nil {
print((err?.localizedDescription)!)
return
} else {
for i in snap!.documentChanges{
let id = i.document.documentID
let name = i.document.get("name") as? String ?? ""
let weight = i.document.get("weight") as? Int ?? 0
let temp = i.document.get("temp") as? Int ?? 0
let time = i.document.get("time") as? Int ?? 0
self.datas.append(Food(id: id, name: name, weight: weight, temp: temp, time: time))
}
}
}
}
}
}
struct ContentView: View {
@ObservedObject var foodDatas = FoodViewModel()
@State private var id = ""
@State public var selection: Int = 0
var body: some View {
NavigationView{
let allFood = self.foodDatas.datas
ZStack {
Color("brandBlue")
.edgesIgnoringSafeArea(.all)
VStack {
Picker(selection: $selection, label: Text("Select your food")) {
ForEach(allFood.indices, id:\.self) { index in
Text(allFood[index].name.capitalized).tag(index)
}
}
.onAppear() {
self.foodDatas.fetchData()
}
Spacer()
NavigationLink(
destination: DetailView(selection: self.$selection),
label: {
Text("Let's make this!")
.font(.system(size: 20))
.fontWeight(.bold)
.foregroundColor(Color.black)
.padding(12)
})
}
在选择器选择了一种食物类型后,我希望它能够显示烹饪时间和温度等其余细节。现在它显示文本部分的“索引超出范围”。
import SwiftUI
import Firebase
struct DetailView: View {
@ObservedObject var foodDatas = FoodViewModel()
@Binding var selection: Int
var body: some View {
NavigationView{
let allFood = self.foodDatas.datas
ZStack {
Color("brandBlue")
.edgesIgnoringSafeArea(.all)
VStack {
Text("Cooking Time: \(allFood[selection].time) mins")
}
}
}
}
感谢我能得到的所有帮助。
解决方案
在您的DetailView
中,您正在创建一个新实例FoodViewModel
:
@ObservedObject var foodDatas = FoodViewModel()
该新实例没有获取任何数据,因此选择的索引超出范围,因为它的数组是空的。
您可以将原始ContentView
的副本FoodDataModel
作为参数传递。
因此,我引用的前一行将变为:
@ObservedObject var foodDatas : FoodViewModel
然后你NavigationLink
会看起来像这样:
NavigationLink(destination: DetailView(foodDatas: foodDatas, selection: self.$selection) //... etc
推荐阅读
- css - 如何将所有元素的样式恢复为默认值?
- android - Frida - 打印类的静态变量
- python - 在 mac 上安装图形工具后,我得到 ValueError: Namespace Gtk not available
- python-3.x - 如何按照我要求的方式取消透视或堆叠 pandas 数据框?
- typescript - 我应该在哪个文件中放置一个返回新子类的开关函数
- c++ - 检查宏参数是允许的参数之一吗?
- c# - mvc 控制器应该只准备数据并将其传递给适当的服务方法调用
- github - 如何查询 GraphQL GitHub API 以找到我的第一个 git 提交?
- c# - ASP.NET Web API 中的可选查询字符串?
- c# - SqlBulkCopy 防止在关系表中插入为空或不为空的数据