Thread
#compose
    Rick Regan

    Rick Regan

    1 year ago
    Inside a composable I can copy text to the clipboard by doing something like 
    LocalClipboardManager.current.setText(AnnotatedString("Copied to clipboard"))
    . But how can I copy to the clipboard from a callback? I want to copy the state of a
    Text
    when a "copy all" icon button is pressed. (The composable
    SelectionContainer
    is not suitable for my app for several reasons.)
    l

    Lukasz Burcon

    1 year ago
    what about passing a mutableState containing the most up-to-date text?
    Rick Regan

    Rick Regan

    1 year ago
    Do you mean have a composable function that generates no UI but takes that mutable state and calls LocalClipboardManager as above? That is an interesting solution except that I worry that "extra" recompositions (we have no control over them) could overwrite the clipboard when it's not supposed to. (Actually, now that I think about it, isn't writing to the clipboard a side effect, and thus to be avoided within a composable in any case?)
    l

    Lukasz Burcon

    1 year ago
    Side effects are nothing bad in Compose when used correctly. What I’d do is having a parent Composable, let’s say a Row in which a
    mutableState
    is defined and remembered. Then that
    mutableState
    would be passed as a parameter both to a TextField and IconButton (or anything you’d like to use). In the TextField you’d have to update the state whenever the text changes, and in the IconButton you’d just have to implement an onClick like this
    val localClipboardManager = LocalClipboardManager.current
    IconButton(
       icon = xxx,
       onClick = {
          localClipboardManager.setText(AnnotatedString("Copied to clipboard"))
       }
    }
    Look how I got the LocalClipboardManager instance outside of the
    onClick
    callback so I can use it in a non-Composable function 🙂
    Rick Regan

    Rick Regan

    1 year ago
    That's a pretty neat trick (localClipboardManager), and side steps the side effect issue. Thanks! My onClick() calls a hoisted function to do the callback processing, so what I did was declare localClipboardManager in the higher level state object that the callback accesses, and initialize it in a high level composable.