Search code examples
androidkotlininheritanceandroid-jetpack-composecomposable

Composable inheritance... how to add padding to inherited content?


I want to do some kind of Composable Inheritance. I need a parent composable with a Scaffold, and the children must have the inner content to the scaffold. How can I apply the innerPadding to the inherited children?

Parent:

@Composable
fun SectionScreen(
    section: Section,
    modifier: Modifier = Modifier,
    content: @Composable (modifier: Modifier) -> Unit,
) {
    Scaffold(
        modifier = modifier,
        topBar = {
            Text(text = "Top Section Header -> sectionID: ${section.sectionID}")
        },
        bottomBar = {
            Text(text = "Top Section Footer -> sectionID: ${section.sectionID}")
        }
    ) { innerPadding ->
        content(Modifier.padding(innerPadding))
    }
}

Children:

@Composable
fun InfoSectionScreen(section: Section, modifier: Modifier = Modifier) = SectionScreen(
    section = section,
    modifier = modifier,
) {
    Column(
        modifier = modifier
    ) {
        Text(text = "Section Content -> sectionID: ${section.sectionID}")
    }
}

As you can see, the issue is in this line:

content(Modifier.padding(innerPadding))

I need to pass the innerPadding but I don't know how to receive it on InfoSectionScreen (editado)


Solution

  • If you use modifier = modifier in InfoSectionScreen then you will use the parameter that was passed to InfoSectionScreen, not the parameter you receive for your lambda. Lambda parameters need to be explicitly named where you want to use them (like innerPadding in SectionScreen), otherwise they default to it:

    Column(
        modifier = it
    ) {
        // ...
    }
    

    But I wouldn't recommend passing a modifier to the lambda in the first place, just do it the same way as the Scaffold does: Pass the PaddingValues so your child composables can decide themselves how to apply them.