我选择了 SelectPost action
个帖子(来自@Composable 屏幕)
mainViewModel.actions.offer(MainAction.SelectPost(post))
我在枚举类中定义了屏幕。有时我想导航到另一个屏幕并在它们之间传递数据。在这种情况下,我想传递 Post
对象
我的视图模型:
class MainViewModel : ViewModel() {
val state = MainViewState()
val actions = Channel<MainAction>()
init {
viewModelScope.launch {
try {
actions.receiveAsFlow().collect { action ->
when (action) {
is MainAction.SelectPost -> {
state.destinationScreen.value = DestinationScreen.POST_DETAILS(action.data)
}
}
}
} catch (e: Exception) {}
}
}
}
enum class DestinationScreen(val data: Any? = null){
DEFAULT,
POST_DETAILS
}
class MainViewState {
val destinationScreen = mutableStateOf(DestinationScreen.DEFAULT)
}
sealed class MainAction {
data class SelectPost(val data: Post) : MainAction()
}
在我的 @Composable 主屏幕中,我观察 viewModel 中的状态,当状态改变时,我想导航到选定的屏幕并将数据传递给它。
@Composable
fun AppNavigationHost() {
val mainViewModel: MainViewModel = viewModel()
val appNavController = rememberNavController()
NavHost(
navController = appNavController,
startDestination = Screens.HOME.title
) {
when (val destination = mainViewModel.state.destinationScreen.value) {
DestinationScreen.POST_DETAILS -> {
composable(DestinationScreen.POST_DETAILS.name) {
PostDetailsScreen(destination.data as Post)
}
}
else -> {}
}
}
}
问题出在这一行:
is MainAction.SelectPost -> {
state.destinationScreen.value = DestinationScreen.POST_DETAILS(action.data)
}
POST_DETAILS
是未解析的引用。由于接收器类型不匹配,以下候选均不适用:
如何为枚举类中的项目设置数据?我应该使用 Pair() 吗?