DEV Community

Max
Max

Posted on Edited on

Jetpack Compose Grid without Lazy

Introduction

For most grid situations we could use LazyVerticalGrid. But not if you want to add the grid to a scrollable column with multiple scrollable elements.

My custom grid-component fixes this exception:
Nesting scrollable in the same direction layouts like LazyColumn and Column(Modifier.verticalScroll()) is not allowed.

Example

Image description

Usage

=> The number of columns can be passed via columns-property.

Column(
    modifier = Modifier
        .fillMaxWidth()
) {
    Text(
        text = "Features",
        style = MaterialTheme.typography.h1,
        modifier = Modifier.padding(15.dp)
    )

    NonlazyGrid(
        columns = 3,
        itemCount = features.size,
        modifier = Modifier
            .padding(start = 7.5.dp, end = 7.5.dp)
    ) {
        FeatureItem(features[it])
    }
}
Enter fullscreen mode Exit fullscreen mode

Implementation

@Composable
fun NonlazyGrid(
    columns: Int,
    itemCount: Int,
    modifier: Modifier = Modifier,
    content: @Composable() (Int) -> Unit
) {
    Column(modifier = modifier) {
        var rows = (itemCount / columns)
        if (itemCount.mod(columns) > 0) {
            rows += 1
        }

        for (rowId in 0 until rows) {
            val firstIndex = rowId * columns

            Row {
                for (columnId in 0 until columns) {
                    val index = firstIndex + columnId
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .weight(1f)
                    ) {
                        if (index < itemCount) {
                            content(index)
                        }
                    }
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
mustapollo profile image
Musta-Pollo • • Edited

You are amazing!

But it is very weird that I couldn't find any official implementation for this.

For example the shrinkWrap parameter on ListView in Flutter.

Collapse
 
fraterboots profile image
abuicke •

Really helped me out, thank you

Collapse
 
_tiagocabral_ profile image
Tiago Cabral •

you deserve eternal glory

Collapse
 
maaxgr profile image
Max •

Glad it helped :)