Skip to main content

Android: Navigation with Hilt + Jetpack Compose

The project is simple: Login screen and a forgot password screen. You can navigate from Login to ForgotPassword.

I feel like I overcomplicated things, but I don't know if (and how) it can be simplified.

The code: LoginRoute.kt

@Composable
fun LoginRoute(
    viewModel: LoginViewModel = hiltViewModel(),
    navController: NavHostController,
) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()

    LoginScreen(
        uiState = uiState,
        onLoginClicked = {
            viewModel.acceptIntent(LoginIntent.LogIn)
        },
        onForgotPasswordClicked = {
            navController.navigate(NavigationDestination.ForgotPassword.route)
        }
    )
}

LoginNavigationFactory:

class LoginNavigationFactory @Inject constructor() : NavigationFactory {

    override fun create(builder: NavGraphBuilder, navController: NavHostController) {
        builder.composable(NavigationDestination.Login.route) {
            LoginRoute(navController = navController)
        }
        builder.composable(NavigationDestination.ForgotPassword.route) {
            ForgotPasswordRoute()
        }
    }
}

Do I really need to pass navController as an argument to the Routes? If I don't do it and simply do rememberNavController in the composable, it gives me NullPointers.

Simon
  • 265
  • 3
  • 12