Tuesday, 2 November 2021

Jetpack Compose Navigation with HiltViewModel: MainActivity does not implement interface dagger.hilt.internal.GeneratedComponent

I created a new composable activity project with the following dependencies:

implementation "androidx.navigation:navigation-compose:2.4.0-alpha09"
implementation "com.google.dagger:hilt-android:2.38.1"
implementation "androidx.hilt:hilt-navigation-compose:1.0.0-alpha03"

Then I created two composables, one with the Hilt's view model:

@Composable
fun Screen1(onClick: () -> Unit) {
    Column {
        Text(text = "Screen 1")
        Button(onClick = onClick) {
            Text("To Screen 2")
        }
    }
}

@HiltViewModel
class Screen2ViewModel @Inject constructor() : ViewModel()

@Composable
fun Screen2(viewModel: Screen2ViewModel = hiltViewModel()) {
    Text(text = "Screen 2")
}

It works if I try to render them. However, when I add the NavController:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val navController = rememberNavController()

            MyApplicationTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    NavHost(navController = navController, startDestination = "screen1") {
                        composable("screen1") {
                            Screen1() {
                                navController.navigate("screen2")
                            }
                        }
                        composable("screen2") {
                            Screen2()
                        }
                    }
                }
            }
        }
    }
}

My app crashes when I go to the screen 2 with the following error:

java.lang.IllegalStateException: Given component holder class com.sample.myapplication.MainActivity does not implement interface dagger.hilt.internal.GeneratedComponent or interface dagger.hilt.internal.GeneratedComponentManager

What am I doing wrong?



from Jetpack Compose Navigation with HiltViewModel: MainActivity does not implement interface dagger.hilt.internal.GeneratedComponent

No comments:

Post a Comment