How to combine multiple Modifier objects in Jetpack Compose?

Viewed 4241

I have a composable that passes a Modifier instance to its child composable as follows:

@Composable
fun MyComposable(
    modifier: Modifier = Modifier,
    content: @Composable BoxScope.() -> Unit,
) {
    Box(
        modifier = modifier.fillMaxWidth(),
        content = content,
    )
}

This adds the fillMaxWidth modifier to the modifier argument. However, this is not the desired behaviour because I would like fillMaxWidth to be the default width, but still allow the caller to override it.

How do I combine/merge the two modifiers while making my local modifiers the default?

3 Answers

You can simply use Modifier.then(otherModifier). Note: Order is important and you might want to consider what you are adding yourself and what you are adding from outside.

composed is used for stateful modifiers like when you want to implement custom touch controls where you will be called every-time anything changes. See Composed Docs

Use the Modifier.composed function.

@Composable
fun MyComposable(
    modifier: Modifier = Modifier,
    content: @Composable BoxScope.() -> Unit,
) {
    OtherComposable(
        modifier = Modifier.fillMaxWidth().composed { modifier },
        content = content,
    )
}

Use the Modifier.then function.

@Composable
fun MyComposable(
    modifier: Modifier = Modifier,
    content: @Composable BoxScope.() -> Unit,
) {
    OtherComposable(
        modifier = Modifier.fillMaxWidth().then(modifier),
        content = content,
    )
}
Related