gpt4 book ai didi

android - 如何将 id 和应用程序传递给 Jetpack Compose 中的 viewModel/viewModelFactory?

转载 作者:行者123 更新时间:2023-12-04 23:41:17 25 4
gpt4 key购买 nike

我使用 Jetpack Compose 和导航 compose,我想将 id 传递给 viewmodel :

class RecallViewModel(private val id:Long,application: Application):AndroidViewModel(application) {
............................
}

可组合功能:
我不知道如何获得 application在可组合功能中:
@Composable
fun RecallScreen(
id:Long,
onEnd:() -> Unit
){
val recallViewModel = viewModel(factory = RecallViewModelFactory(
id = id,application = "i don't know how to get application"))

}

和工厂
class RecallViewModelFactory(private val id:Long,val application: Application):ViewModelProvider.AndroidViewModelFactory(application) {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return RecallViewModel(id,application) as T
}
}

composable(
"${Routes.recall}/{id}",
arguments = listOf(navArgument("id") { type = NavType.LongType })
) {
RecallScreen(
id = it.arguments!!.getLong("id"),
onEnd = {navController.navigateUp()}
)
}

最佳答案

要回答您的问题:您检索 Application来自 LocalContext目的:

val context = LocalContext.current
val application = context.applicationContext as Application
但是,在使用 Navigation Compose 时,您不需要手动将任何参数传递给您的 ViewModel。相反,您可以利用对 SavedState in ViewModels 的内置支持。并添加 SavedStateHandle ViewModel 的参数。 SavedStateHandle是一个键/值映射,它会自动填充目的地的参数。
这意味着您的 ViewModel 变为:
class RecallViewModel(
application: Application,
savedStateHandle: SavedStateHandle
):AndroidViewModel(application) {

// Get your argument from the SavedStateHandle
private val id: Long = savedStateHandle.get("id")

............................
}
而且您不再需要从参数中手动解析您的 ID 或将其传递给您的 ViewModel:
composable(
"${Routes.recall}/{id}",
arguments = listOf(navArgument("id") { type = NavType.LongType })
) {
RecallScreen(
onEnd = {navController.navigateUp()}
)
}
@Composable
fun RecallScreen(
onEnd:() -> Unit
) {
val recallViewModel: RecallViewModel = viewModel()
}

关于android - 如何将 id 和应用程序传递给 Jetpack Compose 中的 viewModel/viewModelFactory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69145407/

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