Jetpack Compose LazyVerticalGrid Within LazyColumn

May 6, 2022

You will bump into the following error as you cannot put a scrollable composable inside another scrollable composable

java.lang.IllegalStateException: Vertically scrollable component was measured with an infinity maximum height constraints, which is disallowed. One of the common reasons is nesting layouts like LazyColumn and Column(Modifier.verticalScroll()). If you want to add a header before the list of items please add a header as a separate item() before the main items() inside the LazyColumn scope. There are could be other reasons for this to happen: your ComposeView was added into a LinearLayout with some weight, you applied Modifier.wrapContentSize(unbounded = true) or wrote a custom layout. Please try to remove the source of infinite constraints in the hierarchy above the scrolling container.

I assume you want to implement LazyColumn where some item consume a full row (LazyColumn), while others use the row as grid items (LazyVericalGrid).

Solution 1: LazyColumn

@Composable
fun TestScreen() {
    val rowItems = listOf("Item 1", "Item 2", "Item 3")
    val gridItems = listOf("Grid 1", "Grid 2", "Grid 3", "Grid 4")

    LazyColumn() {
        items(rowItems) {
            Text(it)
        }

        val cols = 2
        items(gridItems.chunked(cols)) { items ->
            Row {
                for ((index, item) in items.withIndex()) {
                    Box(modifier = Modifier.fillMaxWidth(1f / (cols - index))) {
                        Text(
                            text = item,
                        )
                    }
                }
            }
        }
    }
}

Solution 2: LazyVerticalGrid

@Composable
fun TestScreen() {
    val rowItems = listOf("Item 1", "Item 2", "Item 3")
    val gridItems = listOf("Grid 1", "Grid 2", "Grid 3", "Grid 4")

    val cols = 2
    LazyVerticalGrid(columns = GridCells.Fixed(cols)) {
        rowItems.forEach {
            item(span = { GridItemSpan(cols) }) { Text(it) }
        }

        items(gridItems) {
            Text(it)
        }
    }
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.