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

How to pass id and application to a viewModel/viewModelFactory in Jetpack Compose?(如何将id和应用程序传递给Jetpack Compose中的viewModel/viewModelFactory?)

本文介绍了如何将id和应用程序传递给Jetpack Compose中的viewModel/viewModelFactory?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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()}
            )
        }

推荐答案

要回答您的问题:从LocalContext对象检索Application

val context = LocalContext.current
val application = context.applicationContext as Application
但是,当使用导航合成时,您不需要手动将任何参数传递给您的ViewModel。相反,您可以利用对SavedState in ViewModels的内置支持,并向您的ViewModel添加一个SavedStateHandle参数。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()
}

这篇关于如何将id和应用程序传递给Jetpack Compose中的viewModel/viewModelFactory?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何将id和应用程序传递给Jetpack Compose中的viewModel/viewModelFactory?

基础教程推荐