Is there a way to update padding in a way that ski...
# compose-android
l
Is there a way to update padding in a way that skips recompositions?
👀 1
d
Material's Scaffold changed the way paddings updated recently You could do the same https://github.com/androidx/androidx/commit/843f4e4f4b74a76395a2099a8af92bcd201484dd
s
If you're rapidly changing your
padding
, your use-case might be better implemented with the
layout
modifier. The example in this article, showing how
firstBaselineToTop
is implemented, may help out! https://developer.android.com/develop/ui/compose/layouts/custom
In our app, we use a custom
.layout { }
modifer to adjust a containers position offset without recomposing the container itself
l
I have been using a
Modifier.layout
implementation, but it seems to be causing recompositions.
Maybe I am confused though think smart
s
This is our really simple offset layout, it seems to work well.
Copy code
.layout { measurable, constraints ->
                        // Measure the app bar
                        val placeable = measurable.measure(constraints)

                        // Place it above the screen, according to the scroll offset
                        layout(placeable.width, placeable.height + appBarOffset) {
                            placeable.place(0, appBarOffset)
                        }
                    }
🤝 1
l
This is what I was originally using:
Copy code
/**
 * Helper method to allow padding modifications to skip recompositions.
 */
fun Modifier.padding(
    paddingValuesProvider: () -> PaddingValues,
): Modifier = layout { measurable, constraints ->
    val paddingValues = paddingValuesProvider()
    val topPaddingPx = paddingValues.calculateTopPadding().roundToPx()
    val bottomPaddingPx = paddingValues.calculateBottomPadding().roundToPx()
    val leftPaddingPx = paddingValues.calculateLeftPadding(layoutDirection).roundToPx()
    val rightPaddingPx = paddingValues.calculateRightPadding(layoutDirection).roundToPx()

    val horizontal = (leftPaddingPx + rightPaddingPx).coerceAtLeast(0)
    val vertical = (topPaddingPx + bottomPaddingPx).coerceAtLeast(0)

    val placeable = measurable.measure(constraints.offset(-horizontal, -vertical))

    val layoutWidth = constraints.constrainWidth(placeable.width + horizontal)
    val layoutHeight = constraints.constrainHeight(placeable.height + vertical)

    layout(layoutWidth, layoutHeight) {
        placeable.placeRelative(leftPaddingPx, topPaddingPx)
    }
}