EnvironmentObject used with .sheet or NavigationLink

104 views Asked by At

If I use an ObservedObject using a sheet my app crashes with this error:

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

If I use a NavigationLink with a NavigationStack the app works fine.

For some days I tried to write a little app using EnvironmentObject using .sheet. I always got that error.

Finale I changed my app using NavigationLink and it worked. Here is my short piece of code:

struct ContentView: View {
    
    @State var showInputView = false
    @StateObject var myCars = Cars(autos: [Car( type: "Mercedes"), Car(type: "Porsche"), Car( type: "Audi")])

    var body: some View {
        NavigationStack{
            VStack {
                List(myCars.cars, id: \.id){car in
                    Text(car.type)
                }

                NavigationLink {
                    Inputview()
                } label: {
                    Text("Show Input View")
                }
                Button("Button InputView"){
                    showInputView = true
                }
                .sheet(isPresented: $showInputView){
                    Inputview()
                }
            }
        }
        .environmentObject(myCars)
        .sheet(isPresented: $showInputView){
            Inputview()
        }
        .padding()
    }
        
}

And my second View:

struct Inputview: View {
    @EnvironmentObject var cars: Cars
    var body: some View {
        VStack{
            List(cars.cars, id: \.id){auto in
                Text(auto.type)}

            
        }
    }
}

So if you use the NavigationLink the app works fine and lists the ObservedObject. But if you use the button which uses the sheet you get an error.

The question now is why this error occurs. And is it possible to use sheet with an ObservedObject like this?

1

There are 1 answers

0
Benzy Neez On

My understanding is that a sheet does not inherit the environment of the launching view, so you need to pass on environment objects explicitly. Like this:

.sheet(isPresented: $showInputView){
    Inputview()
        .environmentObject(myCars)
}