Thread 1: Fatal error: No ObservableObject of type MultiCartManager found. A View.environmentObject(_:) for MultiCartManager may be missing as an ancestor of this view.

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())
    }
}
Answered by DTS Engineer in 787633022

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)
    }
}

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)
    }
}

Thread 1: Fatal error: No ObservableObject of type MultiCartManager found. A View.environmentObject(_:) for MultiCartManager may be missing as an ancestor of this view.
 
 
Q