skip to Main Content

I have the following Composable

@Composable
fun ClickableBar(text: String, action: () -> Unit) {
    Row(
        modifier = Modifier
            .height(40.dp)
            .background(color = AppPrimaryGreen)
            .fillMaxWidth()
            .clickable { action },
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(text = text)

        Icon(
            painter = painterResource(R.drawable.icon_arrow_right),
            contentDescription = "",
        )
    }
}

I want to perform action method when that Row is tapped but action gets highlighted and it says The expression is unused.

What I’m doing wrong??

2

Answers


  1. You need to call it like this:

    action()
    

    Since action is a lambda function passed to ClickableBar function, you need to include parentheses when invoking it, just like with any other function call.

    Login or Signup to reply.
  2. There are actually two ways you can do this.

    dev.tejasb proposed the following to invoke the action function by adding parentheses:

    .clickable { action() }
    

    But you can also do this:

    .clickable(onClick = action)
    

    Both options provide a value for the onClick parameter. While the first option creates a new lambda and calls action in it, the second option directly passes action as the parameter. Note that onClick has the type () -> Unit, the same type as action so you can simply assign the parameter as in option 2.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search