androidkotlinandroid-jetpack-composeandroid-jetpackandroid-jetpack-navigation

Navigating Screen with Jetpack Compose


I am working on an app in Jetpack and I want to traverse from one compose screen to another. I have a login compose and I want whenever the button from the login compose is clicked to go to the next compose. I have my data stored in a View Model also, can anyone help?

enter image description here

enter image description here

enter image description here

enter image description here


Solution

  • you can setup your appnavigation like the example below

    @Composable
    fun AppNavigation() {
    val navController = rememberNavController()
    
    NavHost(navController, startDestination = "login") {
        composable("login") {
            LoginScreen(
                viewModel = viewModel,
                onLoginClicked = {
                    // Navigate to the next screen
                    navController.navigate("nextScreen")
                }
            )
        }
        composable("nextScreen") {
            NextScreen()
        }
      }
    }
    

    Then in your mainactivity you can have your appnavigation called in the setcontent like the below

    class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AppNavigation()
        }
      }
    }
    
    1. You can use a nav library like this one i always use dcompose-navigation

    and it gives you the ease to use a function like the below anywhere clickable in your code.

    fun navigateToExample(navController: NavController) {
      val data = // Your optional data
      navigateTo(navController, "key", "destinationRoute", data)
    }