Jetpack compose navigation with hiltViewModel cannot find constructor

123 Views Asked by At

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?

2

There are 2 best solutions below

0
Luca Nicoletti On BEST ANSWER

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

1
Dan A On

Without the full picture it's hard to guess as @Leviathan said. Anyway, the only two think I can think of are

  1. You forgot a dependency inside your module

  2. You forgot to add @AndroidEntryPoint and/or the delegate by viewModels()` when declaring the viewmodel inside the App /Fragment/Screen...

Nothing else comes up in my mind, sorry.