When ever I try to run my program, I get a fatal error that 'A View.environmentObject(_:) for __ may be missing as an ancestor of this view.', and I don't really understand the error.
Here's my code:
import SwiftUI
struct ContentView: View {
@StateObject var storage = Variables()
var body: some View {
AddToScore()
VStack {
Button("remove points") {
storage.score -= 1
}
Text("text text etxt dfahjadfbadful")
}.environmentObject(storage)
}
}
struct AddToScore: View {
@EnvironmentObject var storage: Variables
var body: some View {
VStack {
Text("Point generator")
.font(.title)
HStack {
Button("Get points!") {
storage.score += 1
}
Text("\(storage.score)")
}
}
}
}
class Variables: ObservableObject {
@Published var score = 0
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
What's wrong is that
.environmentObject(storage)is not in range of AddToScore(). They are both 'on the same level'..environmentObject(storage)needs to be on the level above. Like this:You could also add
.environmentObject(storage)directly onAddToScore()(as shown on the comment by Umer Khan).