Learn Courses My Dashboard

EnvironmentObject Error

Here I am again with an error I don’t understand. This relates to IOS Foundations, Mod4: Lesson 6.

The error (screenshot below) wants me to add an EnvironmentObject to the “appropriate preview”. The error results in the inability to preview the list view and the tab view. However, when I run the app on the simulator, I can navigate between views just fine, but the detail view only shows the recipe name and the other info is blank. Screenshots are below for each view’s code.

I have followed all Chris’ instructions for this mod, and the only view to which he did not add an instance of the EnvironmentObject was the detail view. So I added an instance there, but it made no difference. The error persists.

Any help would be greatly appreciated.






As the error indicates, you need to add an environmentObject to your preview structs, not the main Views. Looks like it might be the RecipeListView that is causing the specific issue here.

And in the future, please post your code as text rather than screenshots. You can do this by placing three backticks ``` on the line before and three backticks ``` on the line after in order to nicely format the code. This makes it far easier to read and also makes it easier for other posters to copy/paste the code in order to test solutions and such.

Exactly where am I adding the environment object code. Could you be more specific?

I added the environment objects in the same places where Chris added them. This is what makes me so confused. Why did it work in his app, but not in mine when all the code is exactly the same?

Sorry about not including the the code in the message. Michelle always asks for a screen shot.

You need it in the RecipeListView_Previews, like this:

struct RecipeListView_Previews: PreviewProvider {
    static var previews: some View {
        RecipeListView()
            .environmentObject(RecipeModel())
    }
}

The problem is the RecipeListView accesses a RecipeModel object injected into the environment in the RecipeTabView. But in the preview, there is nothing injecting this object so you have to add it.

1 Like

Thanks so much. I still don’t understand why Chris didn’t need it there. However, I appreciate your help.