Getting weird Error when trying LazyColumn() in Jetpack compose

Viewed 2657

I am trying to run a simple LazyColumn Object, but am unable to run it without this weird error. Here is my code:

@Composable 
fun Test(){
    LazyColumn() {
        Text(text = "Placeholder", fontSize= 30.sp)
        Spacer(modifier = Modifier.padding(10.dp))
    }
}

Here are the errors:

org.jetbrains.kotlin.diagnostics.SimpleDiagnostic@74c0fa2 (error: could not render message)

org.jetbrains.kotlin.diagnostics.SimpleDiagnostic@c077eec3 (error: could not render message)

Is it something wrong with my code, or is it a bug? *I wanted to test the scroll function by copy and pasting the lines after the LazyColumn() statement over and over

3 Answers

With 1.0.0-beta04 you can use:

val itemsList = (0..50).toList()
LazyColumn() {
    items(itemsList) {
        Text(text = "Placeholder", fontSize = 30.sp)
        Spacer(modifier = Modifier.padding(10.dp))
    }
}

In the LazyListScope in order to display the items you have to use one the provided functions:item, items, itemsindexed and stickyHeader.

The error studio should be showing is @Composable invocations can only happen from the context of a @Composable function; this is the error you get when you would compile this function. That Studio shows (error: could not render message) is a known bug that the team is working on.

The reason the compose compiler plugin generates this error is the lambda expected by LazyColumn is not a composable lambda but is the LazyList DSL in which the column is described. For example, something like,

@Composable 
fun Test(){
    LazyColumn() {
        items(10_000) {
            Text(text = "Placeholder $it", fontSize = 30.sp)
            Spacer(modifier = Modifier.padding(10.dp))
        }
    }
}

is probably what you wanted. It doesn't create 10,000 items, it only creates enough to fit on the screen and will create additional rows as needed (discarding rows as they are occluded) up to row 9,999.

Try this:

@Composable 
fun Test(){
    LazyColumn() {
        for (i in 1..10) {
            TestItem(i)
        }
    }
}

@Composable
fun TestItem(i: Int) {
    Text(text = "Placeholder $i", fontSize = 30.sp)
    Spacer(modifier = Modifier.padding(10.dp))
}
Related