Home > Mobile >  How to navigate from a screen to another in Jetpack Compose using navController?
How to navigate from a screen to another in Jetpack Compose using navController?

Time:11-29

I have this structure:

val navController = rememberNavController()
NavHost(
    navController = navController,
    startDestination = "auth"
) {
    composable(
        route = "auth"
    ) {
        AuthScreen(
            navController = navController
        )
    }
    composable(
        route = "profile"
    ) {
        ProfileScreen(
            navController = navController
        )
    }
}

When I first time open the app, I display a screen according to the authentication state:

if (!viewModel.isUserAuthenticated) {
    AuthScreen(navController = navController)
} else {
    ProfileScreen(navController = navController)
}

Which works fine. The problem comes, when I try to sing-in in the AuthScreen:

when(val response = authViewModel.signInState.value) {
    is Response.Loading -> CircularProgressIndicator()
    is Response.Success -> {
        if (response.data) {
            navController.navigate("profile")
            Log.d(TAG, "Success")
        }
    }
    is Response.Error -> Log.d(TAG, response.message)
}

The log statement prints "Success" but it doesn't navigate to the next ProfileScreen. How to solve this?

CodePudding user response:

You can remove that if-else from the setContent. Instead, make ProfileScreen as the home destination and inside it you can check whether user is authenticated or not. If he is not, navigate to the AuthScreen

@Composable
fun ProfileScreen(navController: NavController) {
    LaunchedEffect(Unit) {
        if(!viewModel.isUserAuthenticated) {
            navController.navigate("auth")
        }
    }
}

If user can logout from this screen (i.e. auth state can change), then instead of Unit use viewModel.isUserAuthenticated as the key for LaunchedEffect (assuming that isUserAuthenticated is a State)

  • Related