is there any standard practice for conditional mod...
# compose
m
is there any standard practice for conditional modifiers inside a composable? Something like this:
Copy code
modifier.run { 
    if(featureA){
        modifierX()
    } else{
        this
    }
}
m
That seems reasonable to me to be honest. You could certainly simplify it with an extension function:
Copy code
fun Modifier.conditionalModifier(condition: Boolean, factory: Modifier.() -> Modifier): Modifier =
    if (condition) {
        factory()
    } else {
        this
    }

Modifier.conditionalModifier(true) { height(4.dp) }
j
I believe there is also a
Modifier.then
as seen in the
Surface
composable:
Copy code
modifier                .shadow(elevation, shape, clip = false)
.then(
if (border != null) Modifier.border(border, shape)
else Modifier
)
.background(
color = backgroundColor,
shape = shape
)
☝️ 1
☝🏻 1
m
oh .. so we can use than, an pass Modifier when condition not met. makes sense!
m
yeah. it’s just some nice syntactic sugar instead of the .run block
but the .then works as well, but again, you’re baking in the if statement, which at times can get ugly looking.
i would have named it “when”, but that’s a reserved keyword
m
yes. thanks!
z
If your modifier chain is getting too messy you can factor vals out:
Copy code
val border = if() Modifier.border(…) else Modifier
…
modifier
  .shadow(…)
  .then(border)
  .background…
m
thats quite clever. ya
compose is so well build. The team is awesome
❤️ 1
c
I've made myself a helpful extension function for cases like this.
Copy code
inline fun Modifier.thenIf(
    condition: Boolean, 
    block: ()->Modifier
) = this.then(if(condition) block() else Modifier)
Besides that, using the
.then(if...)
syntax seems to be the most common from the Compose sources
☝️ 1
😍 1
t
@Casey Brooks Really nice one!
w
Copy code
Modifier.then(
    if(condition){
       Modifier.firstModifier()
    }else{
       Modifier
    }
)
I saw this being used inside compose libraries