myanmarking

    myanmarking

    11 months ago
    is there any standard practice for conditional modifiers inside a composable? Something like this:
    modifier.run { 
        if(featureA){
            modifierX()
        } else{
            this
        }
    }
    m

    mattinger

    11 months ago
    That seems reasonable to me to be honest. You could certainly simplify it with an extension function:
    fun Modifier.conditionalModifier(condition: Boolean, factory: Modifier.() -> Modifier): Modifier =
        if (condition) {
            factory()
        } else {
            this
        }
    
    Modifier.conditionalModifier(true) { height(4.dp) }
    Job Guldemeester

    Job Guldemeester

    11 months ago
    I believe there is also a
    Modifier.then
    as seen in the
    Surface
    composable:
    modifier                .shadow(elevation, shape, clip = false)
    .then(
    if (border != null) Modifier.border(border, shape)
    else Modifier
    )
    .background(
    color = backgroundColor,
    shape = shape
    )
    myanmarking

    myanmarking

    11 months ago
    oh .. so we can use than, an pass Modifier when condition not met. makes sense!
    m

    mattinger

    11 months ago
    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
    myanmarking

    myanmarking

    11 months ago
    yes. thanks!
    Zach Klippenstein (he/him) [MOD]

    Zach Klippenstein (he/him) [MOD]

    11 months ago
    If your modifier chain is getting too messy you can factor vals out:
    val border = if() Modifier.border(…) else Modifier
    …
    modifier
      .shadow(…)
      .then(border)
      .background
    myanmarking

    myanmarking

    11 months ago
    thats quite clever. ya
    compose is so well build. The team is awesome
    c

    Casey Brooks

    11 months ago
    I've made myself a helpful extension function for cases like this.
    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
    Tiago Nunes

    Tiago Nunes

    11 months ago
    @Casey Brooks Really nice one!
    w

    Waqas Tahir

    11 months ago
    Modifier.then(
        if(condition){
           Modifier.firstModifier()
        }else{
           Modifier
        }
    )
    I saw this being used inside compose libraries