How to initialize an EnviromentObject within the main App struct?

Viewed 152

I want to initialize an EnviromentObject in the App struct like this:

class SceneOnDisplay: ObservableObject {
    @Published var scene = 0
}

@main
struct MyApp: App {
    @EnvironmentObject var sceneOnDisplay: SceneOnDisplay
    
    var body: some Scene {
        WindowGroup {
            switch sceneOnDisplay.scene{
            case 1:
                PractiseSceneView()
            default:
                ContentView()
            }
        }
    }
}

But because this is the root scene/view & there is no SceneDelegate, I have no where to initialize the EnviromentObject. Therefore I get this error:

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

What should I do?

1 Answers

You can create a top level view specifically for routing:

@main
struct MyApp: App {
    @StateObject var sceneOnDisplay = SceneOnDisplay() // init here

    var body: some Scene {
        WindowGroup {
            RoutingView()
                .environmentObject(sceneOnDisplay) // and pass as an `EnvironmentObject`
        }
    }
}

struct RoutingView: View {
    @EnvironmentObject var sceneOnDisplay: SceneOnDisplay

    var body: some View {
        switch sceneOnDisplay.scene {
        case 1:
            PractiseSceneView()
        default:
            ContentView()
        }
    }
}
Related