Home > Net >  How can you create a reusable modifier in Compose?
How can you create a reusable modifier in Compose?

Time:04-23

Most of my screens(views) start out with a Box composable to contain all the child composables(components).

// background
Box(
        modifier = Modifier
            .fillMaxSize()
            .background(customColor)
    ) 
{
// foreground
Column()

}

Instead of having to create the modifier properties on every screen, how would you create a reusable modifier?

CodePudding user response:

You can create it like this

fun Modifier.myModifier(customColor: Color) = this.then(
    Modifier.fillMaxSize().background(customColor)
)

CodePudding user response:

In such a simple case, you can do the following (no need to use then):

fun Modifier.myModifier(customColor: Color) =
    this.fillMaxSize()
        .background(customColor)

In case you need to save any state in your modifier using remember or other state builders annotated with @Composable, you can do it with Modifier.composed. For example here's how you can add animation to your modifier:

fun Modifier.myModifier(customColor: Color): Modifier = composed {
    val animatedColor by animateColorAsState(customColor)
    this.fillMaxSize()
        .background(animatedColor)
}

Note, that inside composed you should only use state annotated composables, not views. More details can be found here.

  • Related