Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifier doesn't work when used with .apply

Why is it that border modifier is not applied when used with .apply { }?

val selected = remember { mutableStateOf(true) }

val selectableModifier = Modifier
    .padding(horizontal = 5.dp, vertical = 8.dp)
    .apply {
    // this changes, but border is not applied
    println("$selected changed") 
    if (selected) {
        border(
            BorderStroke(1.dp, MaterialTheme.colors.primaryVariant),
            RoundedCornerShape(13.dp)
        )
    }
}
like image 709
Sreekant Shenoy Avatar asked Feb 20 '26 04:02

Sreekant Shenoy


1 Answers

apply always returns this to output. You can change this inside, but in case with modifiers they are immutable, you expected to create a new modifier based on the current one. That's why your border is being ignored.

Instead you can use run, and you have to return something: newly created modifier or this. Check out more about kotlin scope functions.

val selected by remember { mutableStateOf(true) }

val selectableModifier = Modifier
    .padding(horizontal = 5.dp, vertical = 8.dp)
    .run {
        if (selected) {
            border(
                BorderStroke(1.dp, MaterialTheme.colors.primaryVariant),
                RoundedCornerShape(13.dp)
            )
        } else {
            this
        }
    }
like image 191
Philip Dukhov Avatar answered Feb 21 '26 18:02

Philip Dukhov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!