Jetpack Compose Load N Images per Row (Grid of Images)

LazyVerticalGrid

LazyVerticalGrid(modifier = Modifier.padding(4.dp), columns = GridCells.Fixed(2)) {    items(1..10) { imageId ->        val url = "https://picsum.photos/id/$imageId/200/300"        PhotoItem(            modifier = Modifier.padding(4.dp),            data = url        )    }}
@Composablefun PhotoItem(modifier: Modifier = Modifier, data: Any) {    val painter = rememberImagePainter(        data = data,        builder = {            placeholder(R.drawable.placeholder)            // transition when placeholder -> image            crossfade(true)            error(R.drawable.error)        }    )    Image(        painter = painter,        contentDescription = null,        modifier = modifier.aspectRatio(1.0f),        contentScale = ContentScale.Crop    )}

NOTE: https://developer.android.com/jetpack/compose/lists#grids

Custom

Load 3 Grid Images per row

@Composablefun SampleScreen() {    val rowSize = 3    LazyColumn {        (1..10).chunked(rowSize).map { imageIds ->            Row {                for ((index, imageId) in imageIds.withIndex()) {                    val url = "https://picsum.photos/id/$imageId/200/300"                    PhotoItem(                        modifier = Modifier.fillMaxWidth(1f / (rowSize - index)),                        data = url                    )                }            }        }    }}

Grid Composable

@Composablefun <T> Grid(rowSize: Int = 3, chunks: List<List<T>>, content: @Composable() (Int, Int, T, Modifier) -> Unit) {    // val rowSize = 3    chunks.withIndex().map { (rowIndex, items) ->        Row {            for ((colIndex, item) in items.withIndex()) {                content(rowIndex, colIndex, item, Modifier.fillMaxWidth(1f / (rowSize - colIndex)))            }        }    }}

Usage

val images = listOf(...)val rowSize = 3Grid(rowSize, images.chunked(rowSize)) { rowIndex, colIndex, image, modifier ->    PhotoItem(image)}

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.