'Jetpack Compose navigation with arguments

I want to navigate from ViewModelOne to ViewModelTwo where I send data to ViewModelTwo during navigation. This is my navigation sealed class with route and ID argument

sealed class AnimationsNavigation : NavigationAction {
    class PopUpAnimationNavigation(val id: String = "{id}") : AnimationsNavigation() {
        override val route: String
            get() = "animationNavigator/$id"
    }
}

This is my example compose holder, where I pass my backStackEntry


fun NavGraphBuilder.composableHolder(
    action: NavigationAction,
    content: @Composable (NavBackStackEntry) -> Unit
) {
    composable(
        route = action.route,
    ) { navBackStack->
        content(navBackStack)
    }
}

And this is where I used it

private fun NavGraphBuilder.commonDestinations() {
    composableHolder(AnimationsNavigation.PopUpAnimationNavigation()){
        AnimationsNavigator()
    }
}

This is the viewModel I am navigating with the argument I will pass to other screen where I eventually will use it

class OrderDetailScreenViewModel(
    private val navigationDispatcher: NavigationDispatcher
) : ViewModel() {
    
    fun confirmButtonClicked() {
        navigateToAnimation()
    }

    private fun navigateToAnimation() {
        viewModelScope.launch {
            navigationDispatcher.navigateTo(AnimationsNavigation.PopUpAnimationNavigation(id = "here will be posible id"))
        }
    }
}

and this is the viewModel I am trying to get it

class AnimationsViewModel(
    savedStateHandle: SavedStateHandle
) : ViewModel() {
    
    init {
        val id = savedStateHandle.get<String>("id").orEmpty()
    }
}

The problem is that I always get empty string like SaveStateHandle is empty (I saw part of this way for navigation and adapt it to my app), any ideas how I can pass data like that?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source