https://kotlinlang.org logo
#compose
Title
# compose
k

Kshitij Patil

02/18/2021, 11:23 AM
What’s the right way of conditionally adding Modifiers? I tried
Copy code
Modifier.padding()
.preferredSize()
.apply {
    if(<some condition>) {
        this.then(Modifier.clickable { })
    }
}
but didn’t work
d

Denis

02/18/2021, 11:26 AM
g

grandstaish

02/18/2021, 11:27 AM
Copy code
Modifier.padding()
  .preferredSize()
  .then(if (x) Modifier.clickable(...) else Modifier)
👍 2
k

Kshitij Patil

02/18/2021, 11:34 AM
This worked! Any better way where I could write a lambda and don’t need to return default “Modifier” in else part?
g

grandstaish

02/18/2021, 11:40 AM
No, but you can try make it a bit more readable by not inlining the modifier, e.g.:
Copy code
val click = if (x) {
    Modifier.clickable(...) 
} else {
    Modifier
}

Modifier.padding()
  .preferredSize()
  .then(click)
You see this pattern throughout foundational code
👍 1
a

Albert Chang

02/18/2021, 11:53 AM
Use
run
if you want to avoid unnecessary wrapping of the modifier.
k

Kshitij Patil

02/18/2021, 12:21 PM
Okay