I’m navigating to a destination that initially displays a DatePickerModal
, and a set of buttons on the screen. When the user selects a date and clicks on one of the buttons, I want to pass the selected date and the button that was pressed to the ViewModel, so that based on that data, actions can be executed in the data repository.
My problem is that I don’t know how to pass both data at the same time.
These are the relevant parts of my code:
CalendarScreen
@ExperimentalLayoutApi
@ExperimentalCoroutinesApi
@Composable
internal fun CalendarScreen(
viewModel: CalendarViewModel = hiltViewModel()
) {
val selectedTopicId by viewModel.selectedTopicIdd.collectAsStateWithLifecycle()
var showModal by remember { mutableStateOf(true) }
ButtonsScreenCalendar(
onTopicButtonClicked = viewModel::onTopicClick,
onDateSelected = viewModel::onDateSelected
)
var selectedDate by remember { mutableStateOf<Long?>(null) }
if (selectedDate != null) {
val date = Date(selectedDate!!)
val formattedDate = SimpleDateFormat("MMM dd, yyyy", Locale.getDefault()).format(date)
Text("Selected date: $formattedDate")
} else {
Text("No date selected")
}
if (showModal) {
DatePickerModal(
onDateSelected = {
selectedDate = it
viewModel::onDateSelected
showModal = false
},
onDismiss = { showModal = false }
)
}
}
ButtonsScreenCalendar
@ExperimentalLayoutApi
@Composable
fun ButtonsScreenCalendar(
onTopicButtonClicked: (String) -> Unit,
onDateSelected: (Long)-> Unit
) {
/* Some code */
FlowRow(modifier = rowModifier) {
it.items.forEach {
HomeButton(it) {
onTopicButtonClicked(it.id.toString())
onDateSelected
}
Spacer(modifier = chipModifier)
}
}
}
HomeButton
@Composable
fun HomeButton(
itemUI: ItemUI,
onClick: () -> Unit
) {
AssistChip(
onClick = { onClick() },
label = { Text(itemUI.title) }
)
}
CalendarViewModel
@HiltViewModel
class CalendarViewModel @Inject constructor(
private val savedStateHandle: SavedStateHandle,
val universalisRepository: UniversalisRepository,
getTopicWithDate: GetTopicWithDateUseCase,
) : ViewModel() {
private val selectedTopicIdKey = "selectedTopicIdKey"
private val selectedTopicId = savedStateHandle.getStateFlow(
key = selectedTopicIdKey,
initialValue = 1, //TODO
)
//TODO Invoque use case passing topic and date
/* Some code */
fun onTopicClick(topicId: String?) {
savedStateHandle[TOPIC_ID_ARG] = topicId
}
}
In the onTopicClick
method of the CalendarViewModel
I can see the button that was pressed, but I don’t know how to get the date as well.