Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Preview problem with @EnvironmentObject

I am having trouble getting an updated preview when using @EnvironmentObject in my Swift project. In the simulator it works fine, but previewing is not. The error it shows is following:

ASET - Audio System Engineer Tools crashed due to missing environment of type: UserSettings. To resolve this add `.environmentObject(UserSettings(...))` to the appropriate preview.

However, when I try to add it, it keeps on coming with the same issue. Anyone have some helpful advise or solution?

like image 394
Fabian H. Avatar asked Mar 03 '26 10:03

Fabian H.


2 Answers

Found the answer which was already posted on stack overflow: instead of just putting it in the preview struct, I had to declare it like this, which makes the preview update without any issues:

struct CalculatorView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environmentObject(UserSettings())
    }
}
like image 179
Fabian H. Avatar answered Mar 04 '26 23:03

Fabian H.


For those still having issues with the Preview but may not be related to this, you also have to inject it manually into the preview itself since it acts standalone and can't see your injection at the top level.

#Preview {
ContentView()
    .environmentObject(UserAuth())
}
like image 42
builderbob Avatar answered Mar 04 '26 23:03

builderbob