0

I'm trying to implement Grid Layout with 2 columns using Compose, but LazyVertical Grid does not work for me. I searched for some workarounds to fulfill the task, but nothing was rendered on a screen. Any ideas?

 val state = rememberLazyListState()
    LazyVerticalGrid(
        cells = GridCells.Fixed(2),
        state = state,
        content = {
            items(bookList.books){
                bookList.books.map {
                    BookUI(book = it, onClick = {})
                }
            }
        }
    ) 

I tried using LazyVerticalGrid this way, but it does not render a list, while LazyColumn renders it

  • Kindly explain what you are doing with a minimum reproducible example and why "LazyVertical Grid does not work for me". – Abhimanyu Feb 15 '22 at 12:46
  • Post some code if you want to be taken seriously. – Johann Feb 15 '22 at 13:03
  • ` val state = rememberLazyListState() LazyVerticalGrid( cells = GridCells.Fixed(2), state = state, content = { items(bookList.books){ bookList.books.map { BookUI(book = it, onClick = {}) } } } )` this snippet renders nothing, while LazyColumn renders a list – Dato.Beriashvili Feb 15 '22 at 13:03

3 Answers3

2

You don't need a map when using items.

Change

items(bookList.books){
    bookList.books.map {
        BookUI(book = it, onClick = {})
    }
}

to

items(bookList.books){ book ->
    BookUI(book = it, onClick = {})        
}

Don't forget to import,

import androidx.compose.foundation.lazy.items
Abhimanyu
  • 11,351
  • 7
  • 51
  • 121
2

Implementation has changed since the time your question was created, so the following code snipped should work in your case:

val state = rememberLazyGridState()
LazyVerticalGrid(
    state = state,
    columns = GridCells.Fixed(2)
) {
    items(bookList.books) { books ->
       BookUI(book = it, onClick = {})
    }
}
Victor
  • 21
  • 2
1

try to use the following code:

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun MyGrid(items: List<String>) {
    LazyVerticalGrid(
        cells = GridCells.Fixed(count = 2)
    ) {
        items(items) { text ->
            Text(text = text)
        }
    }
}

Few things you should pay attention to:

  • the items(*) {} function need to be imported from androidx.compose.foundation.lazy.items

  • You added @OptIn(ExperimentalFoundationApi::class)

  • rememberLazyListState() is actually a default param so no need to add it.

For the above example you can use something like this:

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun Content() {
    MyGrid(
        items = listOf(
            "Item A",
            "Item B",
            "Item C",
            "Item D",
            "Item E",
            "Item F"
        )
    )
}

And you will get this:

example

42Geek
  • 332
  • 3
  • 7