【问题标题】:indexoutofboundsexception when updating mutableStateListOf更新 mutableStateListOf 时出现 indexoutofboundsexception
【发布时间】:2021-11-18 00:44:29
【问题描述】:

我正在使用 compose 制作应用程序,其中我使用的是 LazyVerticalGrid,但是当我更新 MutableStateListOf 数据时,它会抛出 IndexOutOfBoundsException。如果我使用 if (index < arrayList.size) 一切正常,但我的一些用户仍然收到此异常。

这是我的代码的简化结构。

val loading = mutableStateOf(false)
val arrayList = mutableStateListOf<String>()

fun loadData() {
  coroutineScope.launch(Dispatchers.Default) {
    loading.value = true
    arrayList.clear()
    arrayList.addAll(getData())
    loading.value = false
  }
}

if (loading.value == true) {
  // Loading Placeholder
} else {
  if (arrayList.isEmpty()) {
    // Empty Placeholder
  } else {
    LazyVerticalGrid() {
      items(arrayList.size) { index ->
        // if (index < arrayList.size)
        ItemLayout(arrayList[index]) // This line throw exception
      }
    }
  }
}

编辑:-

arrayListOf 替换mutableStateListOf 解决了我的问题。

【问题讨论】:

  • 不应该是items(arrayList.size-1)吗?
  • 更喜欢使用items 的另一个重载,它接受项目列表。这样你就不用担心索引了。
  • @vincrichaud 不,这是正确的语法。
  • @ArpitShukla,已经尝试了这两种方法,但得到了同样的异常。
  • @PorushManjhi 此异常显示数组的总大小和您在输出中访问的索引。这些价值观是什么?

标签: android kotlin android-jetpack-compose


【解决方案1】:

像这样使用itemsIndexed

   itemsIndexed(arrayList) { index, item ->
          ItemLayout(item)
     }

【讨论】:

  • 已经试过了,不行。
猜你喜欢
  • 2014-12-08
  • 2017-11-18
  • 2014-07-28
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多