[英]How to add item in LazyColumn in jetpack compose?
In the following viewModel code I am generating a list of items from graphQl server在下面的 viewModel 代码中,我正在从 graphQl 服务器生成一个项目列表
private val _balloonsStatus =
MutableStateFlow<Status<List<BalloonsQuery.Edge>?>>(Status.Loading())
val balloonsStatus get() = _balloonsStatus
private val _endCursor = MutableStateFlow<String?>(null)
val endCursor get() = _endCursor
init {
loadBalloons(null)
}
fun loadBalloons(cursor: String?) {
viewModelScope.launch {
val data = repo.getBalloonsFromServer(cursor)
if (data.errors == null) {
_balloonsStatus.value = Status.Success(data.data?.balloons?.edges)
_endCursor.value = data.data?.balloons?.pageInfo?.endCursor
} else {
_balloonsStatus.value = Status.Error(data.errors!![0].message)
_endCursor.value = null
}
}
}
and in the composable function I am getting this data by following this code:在可组合函数中,我通过以下代码获取这些数据:
@Composable
fun BalloonsScreen(
navHostController: NavHostController? = null,
viewModel: SharedBalloonViewModel
) {
val endCursor by viewModel.endCursor.collectAsState()
val balloons by viewModel.balloonsStatus.collectAsState()
AssignmentTheme {
Column(modifier = Modifier.fillMaxSize()) {
when (balloons) {
is Status.Error -> {
Log.i("Reyjohn", balloons.message!!)
}
is Status.Loading -> {
Log.i("Reyjohn", "loading..")
}
is Status.Success -> {
BalloonList(edgeList = balloons.data!!, navHostController = navHostController)
}
}
Spacer(modifier = Modifier.weight(1f))
Button(onClick = { viewModel.loadBalloons(endCursor) }) {
Text(text = "Load More")
}
}
}
}
@Composable
fun BalloonList(
edgeList: List<BalloonsQuery.Edge>,
navHostController: NavHostController? = null,
) {
LazyColumn {
items(items = edgeList) { edge ->
UserRow(edge.node, navHostController)
}
}
}
but the problem is every time I click on Load More
button it regenerates the view and displays a new set of list, but I want to append the list at the end of the previous list.但问题是每次我单击“ Load More
按钮时,它都会重新生成视图并显示一组新列表,但我想将该列表附加到上一个列表的末尾。 As far I understand that the list is regenerated as the flow I am listening to is doing the work behind this, but I am stuck here to get a workaround about how to achieve my target here, a kind hearted help would be much appreciated!据我所知,列表是重新生成的,因为我正在听的流程正在做这背后的工作,但我被困在这里以获得关于如何在这里实现我的目标的解决方法,非常感谢善意的帮助!
You can create a private list in ViewModel that adds List<BalloonsQuery.Edge>?>
您可以在 ViewModel 中创建一个私人列表,添加List<BalloonsQuery.Edge>?>
and instead of而不是
_balloonsStatus.value = Status.Success(data.data?.balloons?.edges)
you can do something like你可以做类似的事情
_balloonsStatus.value = Status.Success(myLiast.addAll(
data.data?.balloons?.edges))
should update Compose with the latest data appended to existing one应该使用附加到现有数据的最新数据更新 Compose
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.