State Management in Jetpack Compose

Sep 10 2024 · Kotlin 1.9.22, Android 34, Android Studio Iguana | 2023.2.1 Patch 2

Lesson 01: Understand State

Demo

Episode complete

Play next episode

Next
Transcript

In this demo, you’ll see how Jetpack Compose uses state to specify how the UI should behave and look.

To follow along, start Android Studio and open the 01-lesson-understand-state/Starter project. Open the SignUpScreen.kt file. The file contains the starter code, which is very straightforward.

It has the SignUpScreen() composable. The composable contains a Text composable and an OutlineTextField() composable that displays an input field for a user to enter the name of a new club member. It also contains a Text composable that displays the name entered in the input field.

Build and run the project. The Wellness Club sign-up form appears on the screen. The text at the bottom says, “New Member Name: Bilbo Baggins.” But new members’ names won’t always be Bilbo Baggins. You’ll update the app to show the name entered.

First, in the SignUpScreen() composable, create a new variable called memberName and assign it an empty string:

var memberName = ""

Change the value of OutlinedTextField composable to the value of memberName. In the onValueChanged callback, assign the value entered in OutlinedTextField to the memberName variable. Finally, change the name displayed by the Text composable to the value stored in the memberName variable.

...

OutlinedTextField(
  value = memberName,
  onValueChange = { newValue ->
    memberName = newValue
  },
  ...
)

...

Text(text = "New Member Name: $memberName")

...

Build and run the project. When you enter the name of a new member, the UI doesn’t update. What’s happening? Is the UI being recomposed with the new value entered?

Stay tuned. You’ll learn the answer and how to show the name entered on the screen in the upcoming lessons.

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion