无法在 Kotlin 的 LazyColumn 中使用列表。

12

我在项目中使用了LazyColumn。当我传递列表时,它会给出错误提示。有人可以指导我这是什么错误吗?

ResultScreen.kt

@Composable
fun ResultScreen(nearestResultList: List<NearestResult>?) {
    LazyColumn(
        Modifier
            .fillMaxSize()
            .background(getBackgroundColor())
    ) {
        items(nearestResultList) { nearestResult ->
            Text(text = "$nearestResult")
        }
    }
}

错误

Type mismatch.
Required:
Int
Found:
List<NearestResult>?

输入图像描述

更新

输入图像描述

6个回答

25

正确的解决方案是使用以下导入:

import androidx.compose.foundation.lazy.items

问题在于接受列表的items函数被定义为扩展函数,因此我们需要导入它以使其可见并可用。

8

因为你的nearestResultList是可为空的,并且在items(...)函数的各种签名/重载中,选择了签名items(size: Int, ...)作为“最匹配”的选项,所以你看到了那个错误。

唯一需要做的事情,就是进行空检查,然后就可以使用任何items(...)签名了。

import androidx.compose.foundation.lazy.items // or auto-fix imports

if (nearestResultList != null) {
    LazyColumn {
        items(nearestResultList) {
            Text(text = it.event, color = Color.White)
        }        
    }
}

你能帮我解决这个问题吗?谢谢。 - Kotlin Learner

2
@Composable
fun ResultScreen(nearestResultList: List<NearestResult>?) {
    Column(
        Modifier
            .fillMaxSize()
            .background(getBackgroundColor())
    ) {
        LazyColumn {
            nearestResultList?.size?.let {
                items(it) { index ->
                    Text(text = nearestResultList[index].event, color = Color.White)
                }
            }
        }
    }
}

1

对于那些可能使用分页库的人,请添加

import androidx.paging.compose.items

我在解决这个导入语句的问题上遇到了困难。我在我的应用级build.gradle文件中使用了implementation "androidx.paging:paging-compose:3.2.1"。所以我是否漏掉了什么? - undefined

0
如果您在使用LazyHorizontalGrid时遇到此问题,请确保导入了以下内容:
import androidx.compose.foundation.lazy.grid.items
如果您在使用LazyRow时遇到此问题,请确保导入了以下内容:
import androidx.compose.foundation.lazy.items

0

更新的解决方案

         LazyColumn {nearestResultList.isNotEmpty() -> {
                items(
                    count = nearestResultList.itemCount,
                    key = nearestResultList.itemKey(),
                    contentType = nearestResultList.itemContentType(
                    )
                ) { index ->
                    val item = nearestResultList[index]
                    if (item == null) {
                       //handle
                    } else {
                        Text(text = it.event, color = Color.White)
                    }
                }
            }}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接