DEV Community

Max
Max

Posted on

9 2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

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 :)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay