GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

SOLVED: Passing @EnvironmentObject to NavigationDestination

Forums > SwiftUI

Hi all,

First post here; I've tried to search but it's not easy, Stack Overflow doesn't have anything. I am trying to do essentially what is demonstrated here: https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views

The child view has just an:

@EnvironmentObject var vm: XcCopilotViewModel

like any other view. However every time it is instantiated, the vm is not found. I've tried appending it to the NavigationStack, NavigationLink, and destination FlightView and it is always not found.

Can anybody see anything obviously wrong here? Thanks.

struct LogbookView: View {
    @EnvironmentObject var vm: XcCopilotViewModel
    @State private var flights: [Flight] = []
    @State private var importerShowing = false

    var body: some View {
        NavigationStack {
            Section {
                if flights.isEmpty {
                    ContentUnavailableView("No flights",
                                           systemImage: "airplane.departure",
                                           description: Text("No flights stored/imported"))
                } else {
                    List {
                        ForEach(flights) { flight in
                            NavigationLink(value: flight) {
                                FlightCard(flight: flight)
                            }
                        }
                        .onDelete(perform: deleteFlight)
                    }
                }
            }
            .navigationTitle("Logbook")
            .navigationDestination(for: Flight.self) { flight in
                FlightView(flight: flight)
            }
        }
        .environmentObject(vm)
    }
}

   

Solved my own problem.

@EnvironmentObject was used within the child view's Init() and not yet available. Moving the logic to .onAppear fixed it.

   

Hacking with Swift is sponsored by try! Swift Tokyo.

SPONSORED Ready to dive into the world of Swift? try! Swift Tokyo is the premier iOS developer conference will be happened in April 9th-11th, where you can learn from industry experts, connect with fellow developers, and explore the latest in Swift and iOS development. Don’t miss out on this opportunity to level up your skills and be part of the Swift community!

Get your ticket here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.