I am trying to do a bit of fancy navigation in SwiftUI using NavigationPath and am having a problem.
I have a root view with includes a button:
struct ClassListScreen: View {
@Bindable private var router = AppRouter.shared
@State private var addCourse: Bool = false
...
var body: some View {
...
Button("Add Class") {
router.currentPath.append(addCourse)
}.buttonStyle(.borderedProminent)
...
.navigationDestination(for: Bool.self){ _ in
ClassAddDialog { course in
sortCourses()
}
}
}
}
router.currentPath
is the NavigationPath associated with the operative NavigationStack. (This app has a TabView and each Tab has its own NavigationStack and NavigationPath).
Tapping the button correctly opens the ClassAddDialog.
In ClassAddDialog is another button:
struct ClassAddDialog: View {
@Bindable private var router = AppRouter.shared
@State private var idString: String = ""
...
var body: some View {
...
Button("Save") {
let course = ...
... (save logic)
idString = course.id.uuidString
var path = router.currentPath
path.removeLast()
path.append(idString)
router.currentPath = path
}.buttonStyle(.borderedProminent)
...
.navigationDestination(for: String.self) { str in
if let id = UUID(uuidString: str),
let course = Course.findByID(id, with: context) {
ClassDetailScreen(course: course)
}
}
}
}
My intent here is that tapping the Save button in ClassAddDialog would pop that view and move directly to the ClassDetailScreen (without returning to the root ClassListScreen).
The problem is that the code inside the navigationDestination is NEVER hit. (I.e., a breakpoint on the if let ...
statement) never fires. I just end up on a (nearly) blank view with a warning triangle icon in its center. (And yes, the back button takes me to the root, so the ClassAddDialog WAS removed as expected.)
And I don't understand why.
Can anyone share any insight here?