Home > front end >  Kotlin how to write two conditionals inside one modifier
Kotlin how to write two conditionals inside one modifier

Time:10-25

How to write two conditionals under one Modifier? For example for .background i have one conditional that handles pressed state and other is just for setting background color depending of passed variants. If code is written with two .background modifier then isPressed part is not working.

 Box(
  Modifier
     .pointerInput(Unit) {
       detectTapGestures(
        onPress = {
         try {
             isPressed = true
             awaitRelease()
         } finally {
           isPressed = false
          }
        },
       )
      }
.background(if (!isPressed) Red else DarkRed)
.background(if (variant == VariantButtons.Primary) Red else if (variant == VariantButtons.Green)  Green else Color.Transparent)
)

CodePudding user response:

If I understand your question correctly you can use only one background modifier and combine statements inside it, just like below:

.background(
    if (isPressed) {
        DarkRed
    } else {
        when (variant) {
            VariantButtons.Primary -> Red
            VariantButtons.Green -> Green
            else -> Color.Transparent
        }
    }
)
  • Related