Hello, I have a `TextField` and a `Button`. Upon a...
# compose
s
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
I'm using this: (on beta1)
Copy code
val focusManager = LocalFocusManager.current
//...
onClick = { focusManager.clearFocus() })
s
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
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
I got this 😄
l
Lol, me too, on the IDE, but command line gives the correct one.
s
Thanks for mention of
CompositionLocal
though, TIL