Search code examples
iosswiftswiftuiswiftui-navigationstack

How to do programmatic navigation in swiftui using navigationstack once state changes?


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


Solution

  • ...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")
        }
    }