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

myanmarking

09/28/2021, 2:08 PM
is there any standard practice for conditional modifiers inside a composable? Something like this:
Copy code
modifier.run { 
    if(featureA){
        modifierX()
    } else{
        this
    }
}
m

mattinger

09/28/2021, 2:15 PM
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

Job Guldemeester

09/28/2021, 2:18 PM
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

myanmarking

09/28/2021, 2:18 PM
oh .. so we can use than, an pass Modifier when condition not met. makes sense!
m

mattinger

09/28/2021, 2:20 PM
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

myanmarking

09/28/2021, 2:28 PM
yes. thanks!
z

Zach Klippenstein (he/him) [MOD]

09/28/2021, 2:32 PM
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

myanmarking

09/28/2021, 2:33 PM
thats quite clever. ya
compose is so well build. The team is awesome
❤️ 1
c

Casey Brooks

09/28/2021, 2:55 PM
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

Tiago Nunes

09/28/2021, 3:06 PM
@Casey Brooks Really nice one!
w

Waqas Tahir

09/29/2021, 5:14 PM
Copy code
Modifier.then(
    if(condition){
       Modifier.firstModifier()
    }else{
       Modifier
    }
)
I saw this being used inside compose libraries