gpt4 book ai didi

kotlin - Jetpack Compose - NavHost 预览问题

转载 作者:行者123 更新时间:2023-12-04 13:51:42 25 4
gpt4 key购买 nike

我今天开始学习jetpack compose,当我使用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)
我的项目代码:
@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) {
...
}
}
}
}
}
当我使用这个时,有什么方法可以修复 Android Studio 上的预览 NavHost ?我正在使用依赖项: implementation "androidx.navigation:navigation-compose:2.4.0-alpha06"

最佳答案

您可以使用的一种技术是为您的屏幕设置一个包装器,您的包装器将从您的 View 模型中获取状态并将其传递给实际屏幕。然后您可以预览采用状态的屏幕,而不是 View 模型。像这样的东西

@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
}

关于kotlin - Jetpack Compose - NavHost 预览问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68719272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com