IllegalArgumentException: Key "1" was already used please make sure you provide a unique key

IllegalArgumentException: key was already used

当使用 LazyColumn/Row 时,其中的 item 需要指定唯一不重复的 key。无论是 Preview 中提供的数据还是运行时的数据,如果提供给 LazyColumn/Row 的 key 出现重复都会抛出相同的异常:

IllegalArgumentException: Key "1" was already used. If you are using LazyColumn/Row please make sure you provide a unique key for each item

  1. 如下面的例子中 Preview 提供给 items 的 key 出现重复,就会出现上图中的 Render problem 异常:
data class Item(
    val id: Int,
    val name: String,
)

@Composable
fun ItemGrid(items: List<Item>) {
    val state = rememberLazyGridState()
    LazyVerticalGrid(
        modifier = Modifier.fillMaxSize(),
        state = state,
        columns = GridCells.Fixed(3),
        contentPadding = PaddingValues(16.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
    ) {
        items(items, { it.id }) { item ->
            Text(text = item.name)
        }
    }
}

@Composable
@Preview
fun PreviewItemGrid() {
    ItemGrid(
        items = listOf(
            Item(id = 1, name = "ItemName1"),
            Item(id = 2, name = "ItemName2"),
            Item(id = 3, name = "ItemName2"),
        ),
    )
}
  1. 下面的错误信息是如果运行时遇到重复 key 抛出的异常:
FATAL EXCEPTION: main
Process: cn.itmob.demo, PID: 6736
java.lang.IllegalArgumentException: Key "1" was already used. If you are using LazyColumn/Row please make sure you provide a unique key for each item.
	at androidx.compose.ui.layout.LayoutNodeSubcompositionsState.subcompose(SubcomposeLayout.kt:410)
	at androidx.compose.ui.layout.LayoutNodeSubcompositionsState$Scope.subcompose(SubcomposeLayout.kt:740)
	at androidx.compose.foundation.lazy.layout.LazyLayoutMeasureScopeImpl.measure-0kLqBqw(LazyLayoutMeasureScope.kt:118)
	at androidx.compose.foundation.lazy.grid.LazyMeasuredItemProvider.getAndMeasure-ednRnyU(LazyMeasuredItemProvider.kt:44)
	at androidx.compose.foundation.lazy.grid.LazyMeasuredLineProvider.getAndMeasure-bKFJvoY(LazyMeasuredLineProvider.kt:78)
	at androidx.compose.foundation.lazy.grid.LazyGridMeasureKt.measureLazyGrid-t5wl_D8(LazyGridMeasure.kt:154)
	at androidx.compose.foundation.lazy.grid.LazyGridKt$rememberLazyGridMeasurePolicy$1$1.invoke-0kLqBqw(LazyGrid.kt:330)
	at androidx.compose.foundation.lazy.grid.LazyGridKt$rememberLazyGridMeasurePolicy$1$1.invoke(LazyGrid.kt:180)
	at androidx.compose.foundation.lazy.layout.LazyLayoutKt$LazyLayout$1$2$1.invoke-0kLqBqw(LazyLayout.kt:71)
	at androidx.compose.foundation.lazy.layout.LazyLayoutKt$LazyLayout$1$2$1.invoke(LazyLayout.kt:69)
	at androidx.compose.ui.layout.LayoutNodeSubcompositionsState$createMeasurePolicy$1.measure-3p2s80s(SubcomposeLayout.kt:598)
	...

作者:ITmob
来源:ITmob.cn
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×