【问题标题】:compose foreach loop:@Composable invocations can only happen from the context of a @Composable functioncompose foreach 循环:@Composable 调用只能在 @Composable 函数的上下文中发生
【发布时间】:2022-01-05 23:19:09
【问题描述】:

我正在尝试迭代 List 的对象,对于我想要显示可组合卡片的每个对象。问题是您不能从 list.forEach{} 括号内调用 Composable 函数。

代码:

@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,

                )
        }
    }
    }
}

【问题讨论】:

    标签: android android-jetpack-compose


    【解决方案1】:

    LazyColumn中有items参数

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

    或者您可以简单地将LazyColumn 更改为Column

    【讨论】:

      【解决方案2】:

      LazyColumn 不提供任何可组合的内容。因此,您必须将可组合函数包装在 items 参数中。

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

      【讨论】:

        猜你喜欢
        • 2020-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-05
        • 1970-01-01
        相关资源
        最近更新 更多