1

Is there an efficient way to make adaptive grid's item height equal to the width determined in runtime? Basically I want square items.

So far I've tried this:

var size by remember { mutableStateOf(IntSize.Zero) }

Column( // item
...
     .onSizeChanged {
        size = it
     }
    .size(with(LocalDensity.current) {
        size.width.toDp()
    })
)

but I'm new to compose and think it might be an expensive operation. Any alternatives?

  • Gabriele Mariotti's answer works best i guess. `Modifier.onSizeChanged` requires one more recomposition since size changes from IntZero to actual size, having one more recomposition doesn't have much effect on performance . However In some cases that change might like a flash or glitch and you have risk of having infinite recompositions, not most of the time but i remember having some infinite recomposition using Modifier.onSizeChanged. You can use BoxWithConstraints or SubcomposeLayout for alternative when size of one Composable effecting another. – Thracian Sep 08 '22 at 19:46
  • https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/package-summary#(androidx.compose.ui.Modifier).onSizeChanged(kotlin.Function1) https://stackoverflow.com/questions/73354911/how-to-get-exact-size-without-recomposition/73357119#73357119 – Thracian Sep 08 '22 at 19:46

1 Answers1

3

You can apply the aspectRatio modifier to the item. For example:

LazyVerticalGrid(
    /* .. */
) {
    items(itemsList) {
        Box(Modifier.aspectRatio(1f)) {

        }
    }
}

enter image description here

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841