android-jetpack-composecompose-desktopjetbrains-compose

How to hide button in Desktop Compose


I am developing an app with Desktop Compose Multi-Platform.
I need to hide the button when it has been clicked. Please see below code:

OutlinedButton(
        onClick = {
            // Perform an operation
            // Hide the button
        }) {
        Text(text = "CLick Here")
    }

As compared to android, Desktop Compose does not have visibility modifiers.
for e.g. visibility = View.GONE

So how to hide the button on the onClick event ?


Solution

  • Any view modifications in Compose are done using state variables.

    If you need the view to be completely removed, you can do it like this:

    var isButtonVisible by remember { mutableStateOf(true) }
    if (isButtonVisible) {
        OutlinedButton(
            onClick = {
                // Perform an operation
                isButtonVisible = false
            }) {
            Text(text = "CLick Here")
        }
    }
    

    If you want to save space in the layout, you can simply hide it with Modifier.alpha. For example, if you have a row with a couple of elements and you don't want them to move after the button disappears.

    var isButtonVisible by remember { mutableStateOf(true) }
    OutlinedButton(
        onClick = {
            // Perform an operation
            isButtonVisible = false
        },
        modifier = Modifier.alpha(if (isButtonVisible) 1f else 0f)
    ) {
        Text(text = "CLick Here")
    }
    

    I suggest you check out with state in Compose documentation, including this youtube video which explains the basic principles.