Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetpack Compose - NavHost preview problem

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"

like image 575
Rafael de Azeredo Avatar asked Aug 09 '21 22:08

Rafael de Azeredo


1 Answers

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
}
like image 195
Francesc Avatar answered Oct 12 '22 10:10

Francesc