How are you supposed to observe in "docked" `DateP...
# compose
p
How are you supposed to observe in "docked"
DatePicker
, if the date was selected? I want to dismiss popup, when the user selects a date. I'm looking at example
DatePickerDocked
here.
k
I don't have the code in front of me, but the datePickerState should have a selectedDateMillis (as shown in the example) which should be a mutableState which you can observe (like
LaunchedEffect(datePickerState.selectedDateMillis)
). Unfortunately this means you can only see when a "click" when a date change occurs. So if the user selects the date which is already selected, no change occurs, so the date picker won't close. Don't know if they introduced a fix for that yet, but that was my problem with it a while ago.
p
That doesn't seem to the case.
DatePickerState
or
rememberDatePickerState
never seem to cause recomposition, not even when date changes.
k
I have this code in my app which uses a material3 DatePicker:
Copy code
val initialSelectedDateMillis: Long? = remember { dateMillis.value }
            val datePickerState = rememberDatePickerState(initialSelectedDateMillis = initialSelectedDateMillis)
            LaunchedEffect(key1 = datePickerState.selectedDateMillis) {
//                logd("date picker state changed: ${datePickerState}")
                if(initialSelectedDateMillis != datePickerState.selectedDateMillis) {
                    dateMillis.value = datePickerState.selectedDateMillis
                    showDatePicker.value = false

                    focusManager.clearFocus() // close keyboard if keyboard is open
                }
            }
Little hard to read maybe, but it uses a LaunchedEffect just like my original answer. This is working in a production app right now
p
I think your code is working purely by chance - triggered by some unrelated recomposition.
selectedDateMillis
is of type
var
, so it won't trigger recomposition on it's own. Source.
k
Are you using rememberDatePickerState? This returns a DatePickerStateImpl: Source. If you look inside the implementation: Source you will see that _selectedDate is a private mutableState and selectedDateMillis is reading that state. So your LaunchedEffect should trigger. If you are not using rememberDatePickerState you can use this function to also get the correct DatePickerStateImpl.