We have a navigation compose library to navigate between screens and send data. Below is the breakdown of how to use this library.
1:- Import this library in build.gradle file
implementation(libs.androidx.navigation.compose)
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
navigationCompose = "2.7.7"
//if you are working with hilt you have to use this as well
implementation ("androidx.hilt:hilt-navigation-compose:1.0.0-alpha03")
2:- Create an enum class to define set of classes
enum class NavigateScreens {
UserScreen,
DetailsScreen;
companion object{
fun fromRoute(rounte:String):NavigateScreens
= when (rounte?.substringBefore("/")){
UserScreen.name ->UserScreen
DetailsScreen.name ->DetailsScreen
null ->UserScreen
else ->throw IllegalArgumentException("Route $rounte is not recognized")
}
}
}
2:- Now create a compose nav graph
@Composable
fun ComposeNavGraph() {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = NavigateScreens.UserScreen.name
) {
// Define your ListScreen route
composable(NavigateScreens.UserScreen.name) {
UserInfoScreen(navController = navController)
}
// Define your DetailsScreen route
val detailName = NavigateScreens.DetailsScreen.name
composable(
route = "$detailName/{bookId}",
arguments = listOf(navArgument("bookId") {
type = NavType.StringType
})
) { backStackEntry ->
val bookId = backStackEntry.arguments?.getString("bookId")
val detailsViewModel = hiltViewModel<DetailsViewModel>()
ReaderBookDetailsScreen(
navController = navController,
bookId = bookId.orEmpty(),
viewModel = detailsViewModel
)
}
}
}
Then you have to use the nav controller in a clickable function like this
Card(
modifier = Modifier
.clickable {
navController.navigate(BookScreens.DetailsScreen.name + "/${book.id}")
}
.fillMaxWidth()
.height(100.dp)
.padding(3.dp),
shape = RectangleShape,
elevation = 7.dp
)