compose foreach loop:@Composable invocations can only happen from the context of a @Composable function

Viewed 3765

I'm trying to iterate over a List of objects, for each of the object I want to display a composable card. The problem is that you cant call Composable functions from inside the list.forEach{} brackets.

The Code:

@Composable
fun Greeting(listy : List<SomethingForLater>) {
  LazyColumn {
    listy.forEach {
        //error here
        testCard(somethingForLater = it)
        }

    }
}
@Composable
fun testCard(somethingForLater: SomethingForLater){
val theme = MaterialTheme
Card(shape = theme.shapes.small,backgroundColor = theme.colors.secondary){
    Column {
        Row {
            Text(
                text = somethingForLater.task,
                modifier = Modifier.padding(start = 5.dp,
                    top = 3.dp,bottom = 3.dp
                ),
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,

                )
        }
    }
    }
}
2 Answers

There is items parameter in LazyColumn

LazyColumn {
        items(listy) { message ->
            testCard(message)
        }
    }

Or you can simply change LazyColumn to Column

LazyColumn does not provide any composable content. So you have to wrap your composable functions inside items parameter.

@Composable
fun Greetings(listy : List<SomethingForLater>) {
  LazyColumn {
    items(listy.size) {
      listy.forEach { somethingForLater ->
        TestCard(somethingForLater = somethingForLater)
      }
    }
  }
}
Related