I’m working on a SwiftUI app where I’m using NavigationPath for navigation. However, when I change the navPath, the navigationDestination isn’t being called, and the screen doesn’t change. Here is my code:
@MainActor
final class Router: ObservableObject, Sendable {
public enum Destination: Codable, Hashable {
case root
case question(id: String)
}
@Published var navPath: NavigationPath
@Published var root: Destination
init(navPath: NavigationPath = NavigationPath(),
root: Destination = .root) {
self.navPath = navPath
self.root = root
}
func navigate(to destination: Destination) {
navPath.append(destination)
}
}
@MainActor
class AppState: ObservableObject {
@Published var router: Router
init(router: Router = Router()) {
self.router = router
}
}
public struct NewReportView: View {
@StateObject var state: AppState
public init() {
let appState = AppState()
self._state = StateObject(wrappedValue: appState)
}
public var body: some View {
NavigationStack(path: $state.router.navPath) {
rootView
.navigationDestination(for: Router.Destination.self) { destination in
DestinationToViewMapper.map(destination: destination)
}
}
.environmentObject(state)
}
}
When I call navigate(to:) on the Router, the navPath is updated, but the corresponding view doesn’t appear. I expect the navigationDestination closure to be called and the view to change accordingly, but nothing happens.
Am I missing something in my implementation, or is there a better way to handle this kind of navigation?
Thanks in advance for your help!