Home > Enterprise >  How to set padding conditionally in jetpack compose
How to set padding conditionally in jetpack compose

Time:11-21

I'm new to jetpack compose. I wanna set different paddings in different conditions.

That's my code.

if(showPadding)
   modifier.padding(2.dp, 2.dp, 4.dp, 8.dp)
else
   modifier.padding(4.dp, 4.dp, 2.dp, 4.dp)


Text(modifier = modifier, ...)

But the result is not as expected.

CodePudding user response:

This can be achieved in two ways:

Using .then():

Text(
    modifier
   .then(
        if(showPadding)
           Modifier.padding(2.dp, 2.dp, 4.dp, 8.dp)
        else
           Modifier.padding(4.dp, 4.dp, 2.dp, 4.dp)
        ),
    ...
)

Using a data class:

data class Padding(
        val start: Int = 0,
        val top: Int = 0,
        val end: Int = 0,
        val bottom: Int = 0
    )

Now create your padding:

var padding = Padding(2, 2, 4, 8)
    if(!showPadding){
        padding = padding.copy(
            start = 4,
            top = 4,
            end = 2,
            bottom = 4
        )
    }

Now set modifier:

Text(
    modifier.padding(
         padding.start.dp,
         padding.top.dp,
         padding.end.dp,
         padding.bottom.dp
        ),
     ...
    )
  • Related