skip to Main Content
struct LoginView: View {

    @State var isUserLoggedIn = false
    
    NavigationStack{
          //.....
          Button {
              Task{
                  await viewModel.doLogin(email: email, password: password)
              }
          } label: {
              Text(Constants.LOGIN)
                .foregroundColor(Constants.BACKGROUND_COLOR)
                .font(Font.custom(Constants.FREDOKA_MEDIUM, size: 25))
                .frame(maxWidth: .infinity)
          }
    }.onChange(of: isUserLoggedIn) { isUserLoggedIn in
        debugPrint(newPasswordValue)
    }
}

I am not able to understand how to write NavigationLink if a state changes, there is no push method in navigation stack as well

2

Answers


  1. ...to do programmatic navigation in swiftui using navigationstack once state changes...,
    try this approach using NavigationPath and navigationDestination

    struct LoginView: View {
        
        @State var isUserLoggedIn = false
        @State var path = NavigationPath()   // <-- here
        
        var body: some View {
            NavigationStack(path: $path) {   // <-- here
                Button {
                    Task {
                        await viewModel.doLogin(email: email, password: password)
                        if isUserLoggedIn {
                            path.append(1)  // <-- here
                        }
                    }
                } label: {
                    Text("Login")
                        .foregroundColor(Constants.BACKGROUND_COLOR)
                        .font(Font.custom(Constants.FREDOKA_MEDIUM, size: 25))
                        .frame(maxWidth: .infinity)
                }
                .navigationDestination(for: Int.self) { _ in     // <-- here
                    NextView()
                }
            }
        }
    }
    
    struct NextView: View {
        
        var body: some View {
            Text("NextView")
        }
    }
    
    Login or Signup to reply.
  2. To add on to workingdog’s answer, navigationDestination’s Type can only be used for one path. If you try to start a new navigationDestination route using Int, you may end up going back to an empty view or get errors.

    Also if you ever need to access the router from different views, you could create an observableObject Router class:

    final class Router: ObservableObject {
        @Published var path: NavigationPath = .init() 
    } 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search