Modifier doesn't work when used with .apply

Viewed 382

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)
        )
    }
}
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
        }
    }
Related