Home > Blockchain >  How to update an item in array with a lazy column item change?
How to update an item in array with a lazy column item change?

Time:12-31

I have a todo list in Jetpack Compose displayed in LazyColumn.

data class TodoItem(val id: Int, val title: String, var urgent: Boolean = false)

val todoList = listOf(
    TodoItem(0, "My First Task"),
    TodoItem(1, "My Second Task which is really very very long. Super long. I mean longer than a line.", true),
    TodoItem(2, "My Third Task"),
)

@Composable
fun MyTodoListView() {
    LazyColumn(modifier = Modifier.fillMaxHeight()) {
        items(items = todoList, itemContent = { item ->
            var checked by remember { mutableStateOf(item.urgent) }
            Row(modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    modifier = Modifier.weight(1f).padding(8.dp),
                    text = item.title)
                Checkbox(
                    checked = checked,
                    onCheckedChange = {
                        checked = it
                        item.urgent = it
                    }
                )
            }
        })
    }
}

When I plan to update the value (through checkbox), I'll have to update is with a separate mutableState variable

onCheckedChange = {
    checked = it
    item.urgent = it
}

Is there a way to make it more direct, with only one variable to change instead of having to change both checked and item.urgent?

CodePudding user response:

You can use an observable MutableList (like a SnapshotStateList) and then update the items by creating a copy.

Something like:

val todoList = remember {
    listOf<TodoItem>(
        TodoItem(0, "My First Task"),
        //...
    ).toMutableStateList()
}


LazyColumn(modifier = Modifier.fillMaxHeight()) {
    items(items = todoList, itemContent = { item ->

        //...
        Checkbox(
            checked = item.urgent,
            onCheckedChange = {
                //checked = it
                val index = todoList.indexOf(item)
                todoList[index] = todoList[index].copy(urgent = it)
            }
        )
        
    })
 }
  • Related