how can I close a `Popup` on hitting Escape key? (...
# compose-desktop
d
how can I close a
Popup
on hitting Escape key? (as the following does not work):
Copy code
Popup(alignment, IntOffset(0, verticalOffset), isFocusable = true) {
        Card(
            Modifier.border(5.dp, Color.LightGray).size(350.dp, 200.dp)
                .onPreviewKeyEvent { when (it.key) {
                    Key.Escape -> {
                        onDismissRequest()
                        true
                    }
                    else -> false
                }}
        ) {
            ...
onPreviewKeyEvent
is never executed
i
This is because
Card
has no focus. Try this:
Copy code
Popup(isFocusable = true) {
    val focusRequester = remember(::FocusRequester)
    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }

    Card(
        Modifier.border(5.dp, Color.LightGray).size(350.dp, 200.dp)
            .focusRequester(focusRequester)
            .focusModifier()
            .onPreviewKeyEvent {
                when (it.key) {
                    Key.Escape -> {
                        onDismissRequest()
                        true
                    }
                    else -> false
                }
            }
    ) {
    }
}
I hope in the future we will come up with something better (
isFocusable
parameter of
Popup
is confusing; and focus requesting is verbose)
1