Tutorial 6

Make screens respond to users.

State is the current truth your UI uses. Events are what users do. Compose redraws the relevant UI when state changes.

State loop

User types
State changes
Composable reads state
UI updates

Do not manually redraw UI. Change state and let Compose call the composable again with the new value.

Input and button state

@Composable
fun AddHabitForm(onAdd: (String) -> Unit) {
    var title by remember { mutableStateOf("") }
    val canSubmit = title.trim().isNotEmpty()

    Column {
        OutlinedTextField(
            value = title,
            onValueChange = { title = it },
            label = { Text("Habit name") }
        )

        Button(
            onClick = {
                onAdd(title.trim())
                title = ""
            },
            enabled = canSubmit
        ) {
            Text("Add")
        }
    }
}

This is the key beginner pattern: UI displays state, user events change state, and Compose updates the UI.

Practice task

  • Create a text field for a course title.
  • Disable the submit button when the field is blank.
  • Show an error message when the title is shorter than three characters.
  • Clear the field after successful submit.

Reference: official Compose state documentation covers state, events, and recomposition as core Compose concepts.