Home > front end >  Why does the author add key(task) for the items function in LazyColumn?
Why does the author add key(task) for the items function in LazyColumn?

Time:12-07

The Code A is from the offical sample project.

I don't understand why the author need to add key(task) for the items function in LazyColumn, could you tell me?

I think the Code B can work well and it's simple.

Code A

val allTasks = stringArrayResource(R.array.tasks)
val tasks = remember { mutableStateListOf(*allTasks) }
...
items(count = tasks.size) { i ->
                val task = tasks.getOrNull(i)
                if (task != null) {
                    key(task) {
                        TaskRow(
                            task = task,
                            onRemove = { tasks.remove(task) }
                        )
                    }
                }
            }

Code B

 ... 
 items(tasks) { task ->
                  TaskRow(
                       task = task,
                        onRemove = { tasks.remove(task) }
                  )
            }

CodePudding user response:

Keys in general are used to avoid unnecessary recompositions. If you have a list of items, and some items are reordered, Compose will find existing components in the composition based on their key and reorder them accordingly instead of recomposing all of them.

That said, items() already supports a key parameter. So code A could indeed be simplified this way if the tasks in the list are non-nullable:

items(tasks, key = { it }) { task ->
    TaskRow(
        task = task,
        onRemove = { tasks.remove(task) },
    )
}

But code B would use the items' positions instead of the items themselves as key by default, which is not desirable.

Disclaimer: I'm no expert in JetPack Compose

  • Related