https://kotlinlang.org logo
s

Syex

03/05/2021, 9:31 AM
Hello, I have a
TextField
and a
Button
. Upon a click on the button I want to clear the focus from the
TextField
so the keyboard disappears. I'm currently trying
Copy code
Button(
    onClick = {
        FocusRequester.Default.freeFocus()
    }
)
This crashes the app with
java.lang.IllegalStateException: FocusRequester is not initialized. One reason for this is that you requesting focus changes during composition. Focus requesters should not be made during composition, but should be made in response to some event.
Is there any other way to achieve this?
Need to add a
Modifier
Copy code
modifier = Modifier
    .focusRequester(FocusRequester.Default)
    .focusable()
And then
requestFocus()
in
onClick()
c

Cyril Find

03/05/2021, 10:07 AM
I'm using this: (on beta1)
Copy code
val focusManager = LocalFocusManager.current
//...
onClick = { focusManager.clearFocus() })
s

Syex

03/05/2021, 10:08 AM
I saw this too, but used it like
Copy code
onClick = { LocalFocusManager.current.clearFocus() }
which just gives you an error without message, but declaring the variable outside works I just saw 🙈
👌 1
l

Landerl Young

03/05/2021, 10:14 AM
The onClick lambda is not @Composable, while LocalFocusManager.current is query Composition Local, which requires a compose context. BTW, this code should not compile… error message: @Composable invocations can only happen from the context of a @Composable function
👌 1
👍 1
s

Syex

03/05/2021, 10:16 AM
I got this 😄
l

Landerl Young

03/05/2021, 10:18 AM
Lol, me too, on the IDE, but command line gives the correct one.
s

Syex

03/05/2021, 10:19 AM
Thanks for mention of
CompositionLocal
though, TIL
15 Views