Search code examples
androidkotlinandroid-jetpackandroid-jetpack-compose

How to combine multiple Modifier objects in Jetpack Compose?


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?


Solution

  • Use the Modifier.composed function.

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