Issue
I have built NavigationRail for my news app that lets me navigate to the search screen and home screen. I am having a problem that the NavController that I passed to my NavigationRail is not giving me an updated current position due to which my navigationRail Icons are not showing that they are selected when at a destination.
Code for my Navigation Rail is:
@Composable
fun NewsNavigationRail(
navController: NavHostController
){
val navigationItems = Destinations.values()
NavigationRail{
navigationItems.filter{
it.icon != null && it.label != null
}.forEach {
NavigationRailItem(
icon = { Icon(
it.icon!!,
contentDescription = it.name
) },
// problematic line --------------------------
selected = navController.currentDestination?.route == it.route,
onClick = {
},
label = { Text(it.label!!) }
)
}
}
}
And code for my NavigationHost is:
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun NavigationHost(){
val navController = rememberNavController()
Row {
NewsNavigationRail(
navController = navController
)
NavHost(navController = navController, startDestination = Destinations.HomeScreen.route){
composable(Destinations.HomeScreen.route){
val newsViewModel = hiltViewModel<NewsViewModel>()
HomeScreen(newsViewModel, navController)
}
composable(
"${Destinations.NewsScreen.route}/{url}",
arguments = listOf(navArgument("url"){
type = NavType.StringType
})
){
val url = it.arguments?.getString("url")
NewsScreen(url)
}
composable(Destinations.SearchScreen.route){
val newsViewModel = hiltViewModel<NewsViewModel>()
SearchScreen()
}
}
}
}
Solution
Try this,
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
Answered By - commandiron
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.