navigationandroid-jetpack-composedagger-hiltjetpack-compose-navigation

Jetpack compose navigation with hiltViewModel cannot find constructor


I have a NavHost in my app defined as follow:

@Composable
fun MainScreen() {
    val navController = rememberNavController()
    Scaffold(
        modifier = Modifier.fillMaxSize(),
        bottomBar = {
            BottomBar(navController = navController)
        }
    ) {
        NavHost(
            modifier = Modifier.padding(it),
            navController = navController,
            startDestination = "main",
        ) {
            navigation("B", route = "main") {
                composable("A") {
                    ScreenA(navigate = { navController.navigate(route = "new") })
                }
                composable("B") { ScreenB() }
            }
            navigation("C", route = "new") {
                composable("C") {
                    ScreenC(onBack = {
                        navController.popBackStack()
                    })
                }
            }
        }
    }
}

Inside ScreenC I have a val viewModel = hiltViewModel<ScreenCViewModel>() (as in ScreenA and ScreenB). The init of ScreenCViewModel causes an exception as it says there is no constructor found for that viewModel. All viewModels are marked with the @HiltViewModel annotation, all dependencies are sorted with @Provides or @Binds. I'm sure I'm missing a tiny bit of configuration for the graph. Any idea?


Solution

  • The problem was totally un-related to navigation, annotations, dependencies or anything you might think about.

    The problematic ViewModel and related Screen (Composable function) were placed in a package named new, in something like this: com.lucanicoletti.app.screens.reminders.new.

    new is a reserved keyword which you can't use in package names, if you try to do so, you'll get a warning warning

    But that's all you'll get. You won't be stopped nor shown any prompt to warn you once more. You're free to hit enter and create that package with that name. Once you do so, you can notice that there is a difference between a valid package name and a non-valid one in the Project Structure of Android Studio: enter image description here