I've started learning today the jetpack compose and I have a render preview problem when I use the NavHost
:
java.lang.IllegalStateException: ViewModels creation is not supported in Preview
at androidx.compose.ui.tooling.ComposeViewAdapter$FakeViewModelStoreOwner$1.getViewModelStore(ComposeViewAdapter.kt:709)
at androidx.navigation.compose.NavHostKt.NavHost(NavHost.kt:103)
at androidx.navigation.compose.NavHostKt.NavHost(NavHost.kt:66)
at com.example.jetpackstudy.ui.activity.BottomNavActivity$AppContentView$1$3$1.invoke(BottomNavActivity.kt:71)
at com.example.jetpackstudy.ui.activity.BottomNavActivity$AppContentView$1$3$1.invoke(BottomNavActivity.kt:70)
My project code:
@Preview @Composable
fun AppContentView() {
JetPackStudyTheme {
val navController = rememberNavController()
Scaffold(topBar = {...})
}, bottomBar = {...}
}) {
Surface(color = MaterialTheme.colors.primary, modifier = Modifier.fillMaxSize()) {
NavHost(navController, startDestination = BotNavItem.Home.route) {
...
}
}
}
}
}
Is there any way to fix the preview on Android Studio when I use this NavHost
? I'm using the dependency:
implementation "androidx.navigation:navigation-compose:2.4.0-alpha06"
A technique you can use is to have a wrapper for your screen, your wrapper would get the state from your viewmodel and pass it to the actual screen. You can then preview the screen that takes the state, not the viewmodel. Something like this
@Composable
fun CityScreen(
viewModel: CityViewModel,
modifier: Modifier = Modifier,
) {
val state = viewModel.state.collectAsState()
CityScreen(
state = state.value,
modifier = modifier,
)
}
@Composable
private fun CityScreen(
state: CityState,
modifier: Modifier = Modifier,
) {
// code here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With