How can I execute something after a Textfield lose...
# compose-desktop
m
How can I execute something after a Textfield loses focus? I tried it like that, but there I have to click a second time to actually get true for the hasFocus state.. so I cant really check if I "lost focus" or "never had focus"
u
Make an remember holder of that state like val isFocus by remember { mutableStateOf(false) inside lambda { isFocus.value = it}
a
You can use this utility:
Copy code
/**
 * Invokes [action] when the [InteractionSource] emits a [FocusInteraction.Focus] and then [FocusInteraction.Unfocus].
 */
@Composable
inline fun InteractionSource.onLostFocus(crossinline action: () -> Unit) {
    LaunchedEffect(this) {
        var hasFocus = false
        interactions.collect { interaction ->
            when (interaction) {
                is FocusInteraction.Focus -> hasFocus = true
                is FocusInteraction.Unfocus -> {
                    if (hasFocus)
                        action()
                    hasFocus = false
                }
            }
        }
    }
}
👍 1
👀 3
create a MutableInteractionSource and pass it to the textfield, then use that function on it