How do I update task completion with state in Jetpack Compose?

In article 3, Task Notes displayed three sample tasks in a scrolling list. Each row showed whether a task was complete. This time, you will add a checkbox to each row and update the completion count as you check and uncheck tasks.

By the end, you will have a screen that reads observable state, sends user events through callbacks, and updates one task without changing its ID.

1. Open the Task Notes project

Continue from article 3. Keep the existing model/Task.kt and data/SampleTasks.kt. The model already supplies a Long ID, a title, and an isCompleted flag. The sample list starts with three tasks, one of which is complete.

If you chose a different package name, keep your package and use the imports for your existing model, sample data, and theme.

2. Replace MainActivity.kt

Open app/src/main/java/org/kodejava/tasknotes/MainActivity.kt and replace its contents with the following code.

package org.kodejava.tasknotes

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card
import androidx.compose.material3.Checkbox
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import org.kodejava.tasknotes.data.sampleTasks
import org.kodejava.tasknotes.model.Task
import org.kodejava.tasknotes.ui.theme.TaskNotesTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        setContent {
            TaskNotesTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    TaskNotesRoute(
                        modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }
    }
}

@Composable
private fun TaskNotesRoute(modifier: Modifier = Modifier) {
    var tasks by remember { mutableStateOf(sampleTasks()) }

    TaskNotesScreen(
        tasks = tasks,
        onTaskCheckedChange = { taskId, isCompleted ->
            tasks = tasks.map { task ->
                if (task.id == taskId) task.copy(isCompleted = isCompleted)
                else task
            }
        },
        modifier = modifier
    )
}

@Composable
private fun TaskNotesScreen(
    tasks: List<Task>,
    onTaskCheckedChange: (Long, Boolean) -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier.fillMaxSize(),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Text(
            text = "Task Notes",
            style = MaterialTheme.typography.headlineMedium,
            modifier = Modifier.padding(
                start = 24.dp,
                top = 24.dp,
                end = 24.dp
            )
        )
        Text(
            text = "Tasks: ${tasks.size} · Completed: ${tasks.count { it.isCompleted }}",
            style = MaterialTheme.typography.bodyMedium,
            modifier = Modifier.padding(horizontal = 24.dp)
        )

        if (tasks.isEmpty()) {
            Text(
                text = "No tasks yet.",
                modifier = Modifier.padding(24.dp)
            )
        } else {
            LazyColumn(
                modifier = Modifier.fillMaxWidth().weight(1f),
                contentPadding = PaddingValues(
                    horizontal = 24.dp,
                    vertical = 16.dp
                ),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                items(
                    items = tasks,
                    key = { task -> task.id }
                ) { task ->
                    TaskRow(
                        task = task,
                        onCheckedChange = { checked ->
                            onTaskCheckedChange(task.id, checked)
                        }
                    )
                }
            }
        }
    }
}

@Composable
private fun TaskRow(
    task: Task,
    onCheckedChange: (Boolean) -> Unit,
    modifier: Modifier = Modifier
) {
    Card(modifier = modifier.fillMaxWidth()) {
        Row(
            modifier = Modifier.fillMaxWidth().padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(6.dp)
            ) {
                Text(
                    text = task.title,
                    style = MaterialTheme.typography.titleMedium
                )
                Text(
                    text = if (task.isCompleted) "Completed" else "Not completed",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            Checkbox(
                checked = task.isCompleted,
                onCheckedChange = onCheckedChange,
                modifier = Modifier.semantics { contentDescription = task.title }
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
private fun TaskNotesScreenPreview() {
    TaskNotesTheme {
        TaskNotesScreen(tasks = sampleTasks(), onTaskCheckedChange = { _, _ -> })
    }
}

@Preview(showBackground = true)
@Composable
private fun EmptyTaskNotesScreenPreview() {
    TaskNotesTheme {
        TaskNotesScreen(tasks = emptyList(), onTaskCheckedChange = { _, _ -> })
    }
}

3. Give the screen one source of state

TaskNotesRoute owns the current list. The first time Compose calls it, remember runs its initializer and stores the state object. On recomposition, Compose reuses that object while the route remains in the composition. mutableStateOf makes changes observable, and the Kotlin by delegate lets you read or assign its value using tasks.

TaskNotesScreen receives the list as a parameter. Both the completion count and the checkboxes read from that same list. The count is computed from the current data, so checking or unchecking a task requires only one state change.

This example keeps edits in memory for the current composition. Rotating a device typically recreates this activity and loads the sample values again. Persistent task storage comes later in the series. See State and Jetpack Compose.

4. Follow a checkbox event

  1. The checkbox displays the value of task.isCompleted.
  2. When the user taps it, onCheckedChange supplies the requested Boolean.
  3. The list passes the task ID and Boolean to the route through onTaskCheckedChange.
  4. The route calls map to build a new list. For the task with that ID, copy(isCompleted = isCompleted) creates a task with the updated flag and preserves the other fields.
  5. The assignment to tasks updates the observed state. Compose can then recompose the UI that read it to display the new checkbox state and count.

Compose calls this pattern state hoisting when a caller owns the state and passes values and callbacks to its children. Here, the row gets its value from the screen, and the event travels back to the route that owns the list. The lazy list continues to use each task’s ID as a stable key. See Compose UI architecture and Checkbox.

5. Verify the result

Run the app in Android Studio on an emulator or phone. Check the following actions in order.

Action Expected result
Launch Task Notes Three rows appear. Only Create the Task model is checked, and the header shows Completed: 1.
Check Learn Kotlin basics Its status becomes Completed, and the header shows Completed: 2.
Uncheck Create the Task model Its status becomes Not completed, and the header shows Completed: 1.
Uncheck Learn Kotlin basics All rows are unchecked, and the header shows Completed: 0. The total remains three.
Relaunch after stopping the app The original sample data appears again.

Use the populated and empty previews to inspect layout, then run the app to verify state changes. The previews pass callbacks with empty bodies. The example was reviewed against the preceding drafts and Android documentation. It still needs a build and emulator check in Android Studio.

If the box changes but the header fails to follow, check that both values come from the list passed to TaskNotesScreen. If neither changes, check that the row forwards the requested Boolean and that the route assigns the result of map back to tasks.

Practice

  1. Display the number of remaining tasks next to the completed count. Derive it from tasks, then verify it updates after every tap.
  2. Give two sample tasks the same title while keeping their IDs distinct. Toggle one and verify that only the row you touched changes. Restore the sample titles afterward.

Gradle dependencies

This example uses the Compose Runtime, Foundation, and Material 3 already available in the Task Notes project. Keep the project’s existing Gradle configuration and Compose BOM. See Set up Jetpack Compose for the official setup instructions.

Next in the series

In article 5, you will add a form for entering a task title, check that it contains text, and put the new task in the list.

Wayan

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.