Syex

    Syex

    1 year ago
    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
    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
    modifier = Modifier
        .focusRequester(FocusRequester.Default)
        .focusable()
    And then
    requestFocus()
    in
    onClick()
    Cyril Find

    Cyril Find

    1 year ago
    I'm using this: (on beta1)
    val focusManager = LocalFocusManager.current
    //...
    onClick = { focusManager.clearFocus() })
    Syex

    Syex

    1 year ago
    I saw this too, but used it like
    onClick = { LocalFocusManager.current.clearFocus() }
    which just gives you an error without message, but declaring the variable outside works I just saw 🙈
    l

    Landerl Young

    1 year ago
    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
    Syex

    Syex

    1 year ago
    I got this 😄
    l

    Landerl Young

    1 year ago
    Lol, me too, on the IDE, but command line gives the correct one.
    Syex

    Syex

    1 year ago
    Thanks for mention of
    CompositionLocal
    though, TIL