How to use the argument that I passed from another screen using compose?

Issue

I want to use accessToken in the AccountListScreen which I pass from AuthenticationScreen

Here is code of my MainActivity:

composable(
    route  Screen.AuthenticationScreen.route
) {
    AuthenticationScreen(navController)
}
composable(
    route  Screen.AccountListScreen.route + "/{accessToken}"
) {
    AccountListScreen(navController)
}

So I’m trying to pass a parameter from my AuthenticationScreen:

@Composable
fun AuthenticationScreen(
    navController: NavController,
    viewModel: AuthenticationViewModel  hiltViewModel()
) {
    val authorizeUrl: String by viewModel.authorizeUrl.observeAsState("")
    WebPageScreen(urlToRender  authorizeUrl, viewModel  viewModel)

    val state  viewModel.state.value
    if (state.accessToken.isNotEmpty()) {
        navController.navigate(Screen.AccountListScreen.route + "/${state.accessToken}")
    }
}

And I don’t understand how I can now get my parameter in AccountListScreen:

@Composable
fun AccountListScreen(
    navController: NavController,
    viewModel: AccountListViewModel  hiltViewModel()
) {

UPDATE

I try to use the @Alpha 1 solution and get the following error maybe I’m doing something wrong

But I have a dependency connected:

implementation “androidx.navigation:navigation-compose:2.4.0-alpha10”

UPDATE 2 enter image description here enter image description here enter image description here

enter image description here

Solution

If you’re using a NavHost, a way could be defining the composable like this in your MainActivity

object composablesData {
    const val ACCESS_TOKEN  "ACCESS_TOKEN"
}

...

composable(
    route  Screen.AccountListScreen.route + "/{$ACCESS_TOKEN}"
) {
    val arguments  requireNotNull(it.arguments)
    val token  arguments.getString(ACCESS_TOKEN) //set the correct type
    AccountListScreen(navController,token)
}

And the just receive the parameter in your composable

@Composable
fun AccountListScreen(
    navController: NavController,
    token: String,
    viewModel: AccountListViewModel  hiltViewModel()
) {

Check Navigate with arguments for more details and examples

Answered By – Stefano Sansone

Leave a Comment