[英]Type 'Void' cannot conform to 'View' | Swift
I'm trying to create a List with data from my firebase reali-time database but i'm getting this error on the List line:我正在尝试使用我的 firebase 实时数据库中的数据创建一个列表,但我在列表行中收到此错误:
The error:错误:
Type 'Void' cannot conform to 'View'
My code: struct ActiveGoalsView: View {我的代码: struct ActiveGoalsView: View {
@State var goals = ["finish this project"]
@State var ref = Database.database().reference()
var body: some View {
NavigationView {
List {
ref.child("users").child(Auth.auth().currentUser?.uid ?? "noid").child("goals").observeSingleEvent(of: .value) { snapshot in
for snap in snapshot.children {
Text(snap.child("title").value)
}
}
}.navigationBarHidden(true)
}
}
}
struct ActiveGoalsView_Previews: PreviewProvider {
static var previews: some View {
ActiveGoalsView()
}
}
You can't use imperative code like observeSingleEvent
in the middle of your view hierarchy that doesn't return a View
.您不能在不返回View
的视图层次结构中间使用像observeSingleEvent
这样的命令式代码。 As a commenter suggested, you'd be better off moving your asynchronous code outside of the body
(I'd recommend to an ObservableObject
).正如评论者所建议的那样,您最好将异步代码移到body
之外(我建议使用ObservableObject
)。 Here's one solution (see inline comments):这是一种解决方案(请参阅内联评论):
class ActiveGoalsViewModel : ObservableObject {
@Published var children : [String] = []
private var ref = Database.database().reference()
func getChildren() {
ref.child("users").child(Auth.auth().currentUser?.uid ?? "noid").child("goals").observeSingleEvent(of: .value) { snapshot in
self.children = snapshot.children.map { snap in
snap.child("title").value //you may need to use ?? "" if this returns an optional
}
}
}
}
struct ActiveGoalsView: View {
@State var goals = ["finish this project"]
@StateObject private var viewModel = ActiveGoalsViewModel()
var body: some View {
NavigationView {
List {
ForEach(viewModel.children, id: \.self) { child in //id: \.self isn't a great solution here -- you'd be better off returning an `Identifiable` object, but I have no knowledge of your data structure
Text(child)
}
}.navigationBarHidden(true)
}.onAppear {
viewModel.getChildren()
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.