I am new to jetpack Composable. I'm trying to build a new app using Composables in MainActivity. so there will be only one activity and no fragments and all Composables. I want to know do I have to pass the navController to all the Composables as parameter so inside the function,I can jump to other composables. cause I dont find a way to obtain the controller inside my composable function. hope you can help me. thanks a lot
MyApp.kt without a class
@Composable
fun MyApp() {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "home_page") {
composable("home_page") {
HomePage(HomePageData())
}
composable("login_page") {
LoginPage(navController)
}
}
}
HomePage.kt without a class
@Composable
fun HomePage(viewModel: HomePageData) {
Surface {
//val navController = rememberNavController()
//with this remeberNavController(). I got another object other than the one in MyApp(). using this controller, some nullPointExpception throwed.
Text(viewModel.pageText, Modifier.clickable {
//I want to navigate to LoginPage upon this click.
})
}
}
here's my code. My problem is that I dont know how to do the jump in the click scope .
Jetpack Compose is mostly a
single-activityapplication so you can manage navigation between the screens.Here is the solution. The
NavControlleris the central API for the Navigation component. It is stateful and keeps track of the back stack of composables that make up the screens in your app and the state of each screenFor better
Routingand to avoid any typo errors we are usingSealed Class.Step 1 :
Screens.ktOnce You define your routing. now it's time to define the
NavHostwhich works as a screen container where you can switch between screens suingNavController. Let's see how It works.Step 2 : In you
MainActivitymake a composable which will holdsNavHost.Here, we have taken
navControllerwhich will manage screen transitions.NavHostneeds a starting or initial screen so we have givenHomeas a starting screen.Step 3 : Define your screens
HomeScreen
LoginScreen
Note: When you want to navigate to a specific route pass it as a lambda parameter and then
navController.navigate(route)will take you to that screen.