Fairly new to SwiftUI and using it for a school project. I keep getting this error and I have no idea how to fix it.
// AddToCartButton.swift
// ProducePal
//
import SwiftUI
struct AddToCartButton: View {
@EnvironmentObject var multicart: MultiCartManager
var product: Product
var body: some View {
VStack {
Button {
multicart.addToCart2(product: product)
} label: {
Text("Add to Cart")
.font(.headline)
.fontWeight(.semibold)
.foregroundColor(.white)
.padding()
.padding(.horizontal, 20)
.background(Color.blue)
.cornerRadius(10)
.shadow(radius: 20)
}
}
.buttonStyle(PlainButtonStyle())
}
}
struct AddToCartButton_Previews: PreviewProvider {
static var previews: some View {
AddToCartButton(product: productList[0])
.environmentObject(MultiCartManager())
}
}
It seems that you are not passing an instance of MultiCartManager into the Environment using .environmentObject(_:)
modifier.
When you use @EnvironmentObject
property wrapper in a view, you need to instantiate the object and be sure to set a corresponding model object on an ancestor view by calling its environmentObject(_:) modifier.
For example:
struct ContentView: View {
@StateObject var multicart = MultiCartManager()
var body: some View {
AddToCartButton()
.environmentObject(multicart)
}
}