Ruben Quadros
11/05/2021, 1:58 PMI keep getting java.lang.IllegalArgumentException: Key was already used. If you are using LazyColumn/Row please make sure you provide a unique key for each item.
I am sure all the keys are unique and I even logged them to be sure. Also this happens when items are rapidly added to lazy column.
Here is my sample code:
@Composable
fun UiComponent() {
LazyColumn(
verticalArrangement = Arrangement.spacedBy(12.dp),
state = scrollState,
reverseLayout = true
) {
items(
items = viewmodel.messages,
key = { item -> item.hashcode() },
itemContent = { item: Entity ->
if (item.isDeleted) {
//show deleted ui
} else {
//show messages
}
})
}
}
}
VM {
init {
observeDataFromDB()
}
private val _messages: MutableList<Entity> = mutableStateListOf()
val messages: List<Entity> = _messages
fun observeDataFromDB() {
viewModelScope.launch {
repo.getData().collect {
_messages.apply {
addNewItem(it)
}
}
}
}
}
//extensions
fun MutableList<Entity>.addNewItem(entity: Entity) {
if (this.size >= MAX_SIZE) {
removeLast()
}
Log("existing ${this.toList().map { "${it.hashCode()}" }}")
Log("adding new ${entity.hashCode()}")
this.add(0, entity)
}
//id is primary key
data class Entity(val id: String, val isDeleted: Boolean, val message: String)
Any help would be great! Have been stuck with this for sometime now and not sure how to proceed 😭
Have tried using id
as the key and I still get the same error.Alejandro Rios
11/05/2021, 2:02 PMRuben Quadros
11/05/2021, 2:04 PMRuben Quadros
11/05/2021, 2:05 PM