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
Ume Channel
04/03/2024, 6:40 PM
Make an remember holder of that state like val isFocus by remember { mutableStateOf(false)
inside lambda { isFocus.value = it}
a
Alexander Maryanovsky
04/03/2024, 7:57 PM
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
Alexander Maryanovsky
04/03/2024, 7:58 PM
create a MutableInteractionSource and pass it to the textfield, then use that function on it