How to change passed-in modifier before using it?

Issue

I’m trying to add some conditional logic to the modifier parameter in my custom composable before using it. How can this be done? For example

@Composable
fun MyComposable(index: Int, myModifier: Modifier = Modifier) {

    if (index == 0) {
        myModifier.background(Color.Red)
    } else {
        myModifier.background(Color.Blue)
    }

    Column(modifier = myModifier) { 
        ...
    }

Compose simply ignores changes made to myModifier

For now, I’m creating a new variable of type Modifier and using that instead, but I’m wondering if there is a better way using the original passed-in modifier.

Solution

I figured out how to do this. Modifier has an infix function .then() that concatenates Modifiers. So in my example, the right way to do this would be:

@Composable
fun MyComposable(index: Int, myModifier: Modifier = Modifier) {

    val backgroundMod = if (index == 0) {
        Modifier.background(Color.Red)
    } else {
        Modifier.background(Color.Blue)
    }

    Column(modifier = myModifier.then(backgroundMod)) { 
        ...
    }

This will keep the passed-in modifier and concatenate the background color Modifier to it.

Answered By – AtomicStrongForce

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *