6

There seems to be a bug in #SwiftUI where @EnvironmentObject will be no longer available if the user pulls down a modal sheet to close it, but cancels the gesture leaving it open.

Actual error:

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

It doesn't happen all the time, but finding it not too hard to reproduce. Does anyone know of a fix?

Eneko Alonso
  • 18,884
  • 9
  • 62
  • 84

1 Answers1

3

Just append a .environmentObject(env) to the presented sheet and it fixes your problem.

In more detail:

@EnvrironmentObject var currentEnvironment: SomeEnvironment
@State var isSheetPresented: Bool = false

var body: some View {
    VStack {
        // ...
    }
    .sheet(isPresented: $isSheetPresented) {
        OtherView()
            .environmentObject(currentEnvironment)
    }
}

To reproduce the issue, you can use the drag gesture to drag the sheet halfway to close it, and just release it. (in a way that it does not close...)

About the situation, I once read that it is somehow a bug. But I also read that this is intended. To me, it seems that it is a bug because the condition that it happens in, feels not right to me.

MrAlirezaa
  • 328
  • 3
  • 9