Home > front end >  How to set conditional properties?
How to set conditional properties?

Time:11-17

In Kotlin and using Jetpack Compose I have lots of code like:

Box(
            modifier = Modifier
                .fillMaxHeight()
                .requiredWidth(expandedSize)
                .align(Alignment.Center)
        )

But a lot of time I would like to set a property depending on a condition:

if(isFlag){
    Box(
                modifier = Modifier
                    .fillMaxHeight()
                    .requiredWidth(expandedSizeA)
                    .align(Alignment.Center)
            )
} else {
    Box(
                modifier = Modifier
                    .fillMaxHeight()
                    .requiredWidth(expandedSizeB)
                    .align(Alignment.Center)
            )
}

or conditions like either requiredWidth() or padding()

if(isFlag){
    Box(
                modifier = Modifier
                    .fillMaxHeight()
                    .requiredWidth(expandedSizeA)
                    .align(Alignment.Center)
            )
} else {
    Box(
                modifier = Modifier
                    .fillMaxHeight()
                    .padding(80.dp, 30.dp, 80.dp, 0.dp)
                    .align(Alignment.Center)
            )
}

I would bet there is an elegant Kotlin way to do so?

CodePudding user response:

For you first case, you can use if statement inside requiredWidth:

Box(
    modifier = Modifier
        .fillMaxHeight()
        .requiredWidth(if(isFlag) expandedSizeA else expandedSizeB)
        .align(Alignment.Center)
)

For the second case, use let or run.

Box(
    modifier = Modifier
        .fillMaxHeight()
        .run {
            if(isFlag) requiredWidth(expandedSizeA)
            else padding(80.dp, 30.dp, 80.dp, 0.dp)
        }
        .align(Alignment.Center)
)

And actually there's a third case as well when you want to either apply or ignore a particular Modifier based on a condition. You can do this with the let or run statements but using an extension function can make the code a little cleaner.

fun Modifier.modifyIf(condition: Boolean, modify: Modifier.() -> Modifier) = 
    if (condition) modify() else this

Usage:

Box(
    modifier = Modifier
        .fillMaxWidth()
        .modifyIf(featureIsEnabled) {
            clickable(onClick = handleClick)
        }
        .padding(24.dp)
)

Here the box will be clickable if featureIsEnabled is true, otherwise not.

  • Related