I am using Jetpack Compose and noticed that the preview is not shown. I read articles like this, but it seems my problem has a different root cause. Even I added defaults to all parameters in the compose function like this:
@OptIn(ExperimentalLifecycleComposeApi::class)
@Composable
@ExperimentalFoundationApi
@Preview
fun VolumeSettingsScreen(
speech: SpeechHelper = SpeechHelper(), // my class that converts text to speech
viewModel: VolumeSettingsViewModel = hiltViewModel(), // using Hilt to inject ViewModels
navController: NavHostController = rememberNavController() // Compose Navigation component
) {
MyAppheme {
Box(
...
)
}
}
When I rollbacked some changes I realized that the @Preview does not support the viewModels regardless of whether they are injected with Hilt or not.
Any Idea how this could be fixed?
I managed to visualize the preview of the screen, by wrapping the ViewModels's functions into data classes, like this:
I passed not the ViewModel directly in the compose but needed functions in a Data class for example, like this:
I made a method that generates those callbacks in the ViewModel, like this:
In the NavHost I hoisted the creation of the ViewModel like this:
It is a bit complicated, but it works :D. I will be glad if there are some comets for improvements.