Once again I have stumbled onto something I don’t understand.
In the entry point for my app I set a NavigationContext in the environment, and when I run the app and navigate between views, at some random point, it throws the error in the second image, and the debugger indicates it is on the “struct FooApp: App {“ line.
What is going on? Help!
In the subviews I am accessing the context from the env like so: “@ Environment(NavigationContext.self) var context”.
@nerdd Environments are not shared to sheets and fullScreenCovers. You have to re-add them to those. Without having seen your whole code, that sounds like the issue.
@melgu Interesting! I don’t think I use fullScreenCovers (I haven’t written it anywhere in the source at least). I only have two views in sheets, and they don't use the NavigationContext.
Is there some way to figure out which view is missing the NavigationContext, or do I just have to re-add it, until the error disappears?
@nerdd I thought that the Xcode debugger would indicate the crash at the point where the environment is missing, but maybe not
@melgu It does, the debugger breaks at the “struct FooApp: App {“ line. If I enable backtrace in the editor, it is the only callsite in my code on the call stack, the rest is in SwiftUI, AppKit, etc.
@nerdd Hm, in that case you have to go through your calls to that environment object and add prints or breakpoints
@melgu Haha, dammit! Come to think of it I might actually not need the navigation context in most of the views
@nerdd Set the environment on ContentView. Then it will be available to ContentView and all its subviews.
@troz Thanks, I just tried that. But I still get the same error. Is there a way to figure out which view is missing the NavigationContext object?
@nerdd Not that I know of. I would search the code for ‘context’ and check that you have declared the Environment property in each view that uses it.
Also, do you have any views that are not subviews of ContentView?
@troz No, they are all nested inside ContentView.
But having thought about it, I’m not so sure, I actually need a navigation context at all. I might just remove it instead.
@nerdd Very perplexing. But if you can delete it, then great. Less code is better code.
@troz Yeah, absolutely! And global state like that is usually just a disaster waiting to happen.