@EnvironmentObject crashes View when presented with PresentationButton

When presenting this view with a PresentationButton it crashes the preview and the Simulator. When presented with a NavigationButton, it works fine. Is this intended behavior? Should EnvironmentObject not work with modal presentations?


import SwiftUI

struct AddListView : View {
    
    @EnvironmentObject var listStore: LinkListStore // Cause of crash
    
    var body: some View {
       Text("HELLO")
    }
}

#if DEBUG
struct AddListView_Previews : PreviewProvider {
    static var previews: some View {
        AddListView()
            .environmentObject(LinkListStore())
    }
}
#endif
Post not yet marked as solved Up vote post of ps3zocker Down vote post of ps3zocker
4.9k views

Replies

I had a similar issue with one of the projects Apple posted online. I think it was Handling User Input tutorial Apple posted that crashes.

I had the same issue, in modal view you have to pass the einvoriment object again it does not inherits like in navigation view.

I dont know if it's a bug but this will fix you problem:


When uou presenting your modal view, just passa again the einvoirment like so:


PresentationButton(Text("add list view"), destination: AddListView().environmentObject(Object()))

This fixes the crash but also changes the behavior.


When using NavigationButton I don't pass anything and it automatically uses the correct object.

When using PresentationButton and passing .environmentObject(ListStore()) then it won't crash but also the data will not refresh. I would have to pass .environmentObject(listStore) for it to work. That dimishes the use of EnvironmentObject though, if I unterstand the concept correctly. Maybe someone can shed light on this:


Let's say I have a two views. "A" has a list with a plus button which can add items. In that case I can just use an EnvironmentObject, pass it to the add item view and "A" will refresh accordingly. What happens if I have "B", let's say in a tab bar, completely disconnected from "A" and want to add items from there? "A" will not update it's list. I thought I can just do .environmentObject(ListStore()) and it will do the right thing. Apperantly that's not the case.

That is the way Apple has demonstrated its use, but the environment object so far has been signifcantly buggy. For me, calling the environmentObject modifier more than once causes SwiftUI to fail resubscribing to the bindable object (I'm seeing two cancel messages instead of one). This creates an effect as if parts of my UI have become paralyzed. The only fix I've found is setting all environment objects at the root view of the UIScene where I know the body won't get called a second time.


Right now, all we can do is submit tickets and hope the next beta fixes some of these issues.