0
0
Android Kotlinmobile~5 mins

Item keys for performance in Android Kotlin

Choose your learning style9 modes available
Introduction

Using item keys helps Android know which list items changed. This makes your app faster and smoother.

When showing a list of messages that can update often.
When displaying a list of contacts that users can add or remove.
When you have a list of products that can be filtered or sorted.
When you want to animate changes in a list smoothly.
Syntax
Android Kotlin
data class Item(val id: Int, val name: String)

val items = listOf(Item(1, "Apple"), Item(2, "Banana"))

// Use 'id' as a key to identify each item uniquely

Keys should be unique and stable for each item.

Use IDs or unique strings as keys, not list positions.

Examples
Use userId as a key to identify each user uniquely.
Android Kotlin
data class User(val userId: String, val username: String)

val users = listOf(User("u1", "Alice"), User("u2", "Bob"))
Use productId as a stable key for each product.
Android Kotlin
data class Product(val productId: Int, val title: String)

val products = listOf(Product(101, "Shoes"), Product(102, "Hat"))
Sample App

This example shows a list of fruits using their id as keys. This helps Compose track each item efficiently when the list changes.

Android Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable

data class Fruit(val id: Int, val name: String)

class MainActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val fruits = listOf(Fruit(1, "Apple"), Fruit(2, "Banana"), Fruit(3, "Cherry"))
    setContent {
      FruitList(fruits)
    }
  }
}

@Composable
fun FruitList(fruits: List<Fruit>) {
  LazyColumn {
    items(fruits, key = { it.id }) { fruit ->
      Text(text = fruit.name)
    }
  }
}
OutputSuccess
Important Notes

Always use a unique and stable key to avoid UI glitches.

Do not use list index as a key because it can change when items move.

Keys help the system reuse UI components and improve performance.

Summary

Item keys uniquely identify list items for better performance.

Use stable IDs or unique strings as keys, not positions.

Keys help smooth animations and efficient updates in lists.