According to this post, starting with version 2.8.0-alpha08 of Navigation, objects can be used in navigation.
I’m trying to implement it, because I need to pass instances of an object called ItemUI
instead of passing a simple value, but it doesn’t work for me.
This is what I’ve been trying:
ForYouNavigation
fun NavController.navigateToForYou(navOptions: NavOptions) = navigate(FOR_YOU_ROUTE, navOptions)
@ExperimentalMaterial3AdaptiveApi
fun NavGraphBuilder.forYouScreen(onTopicClick: (ItemUI) -> Unit) {
composable(
route = FOR_YOU_ROUTE,
) {
ForYouRoute(onTopicClick = onTopicClick)
}
}
NiaNavHost
@Composable
fun NiaNavHost(
appState: NiaAppState,
onShowSnackbar: suspend (String, String?) -> Boolean,
modifier: Modifier = Modifier,
startDestination: String = FOR_YOU_ROUTE,
onReaderClick: () -> Unit
) {
val navController = appState.navController
NavHost(
navController = navController,
startDestination = startDestination,
modifier = modifier,
) {
forYouScreen(onTopicClick = navController::navigateToTodays)
// ...
}
navigateToTodays
fun NavController.navigateToTodays(topicId: ItemUI? = null, navOptions: NavOptions? = null) {
navigate(topicId, navOptions)
}
At this line
navigate(topicId, navOptions)
I have this error:
Type mismatch: inferred type is ItemUI? but TypeVariable(T) was expected
I am following the navigation style shown in the Now In Android app.
navigate
does not accept nullable objects – what it is complaining about is that your navigateToTodays
method is passing navigate
a ItemUI?
– a nullable object and not an ItemUI
.
Since your onTopicClick
correctly uses a non-null ItemUI
type, you should change your method to also take a non-null ItemUI
:
fun NavController.navigateToTodays(topicId: ItemUI, navOptions: NavOptions? = null) {
navigate(topicId, navOptions)
}