In this demo, you’ll learn how to use mutableStateOf and remember functions to store and update state in Jetpack Compose.
Start Android Studio and open the 02-remember-state-variables/Starter project. Then, open the SignUpScreen.kt file, which contains the starter code for this lesson.
The SignUpScreen composable contains the memberName variable. This variable’s value updates when a user enters the new member’s name.
Inside the onValueChanged callback, the name a user enters is assigned to the memberName variable. Then, the new member’s name is displayed on the screen.
Build and run the project.
Notice that nothing changes when you enter a new member’s name. Investigate the code.
memberName is stored in a String container. A String isn’t an observable data type. Hence, Compose isn’t notified when the value of the memberName changes. So, recomposition doesn’t take place, and the UI doesn’t update.
To fix this, you’ll store the value of memberName in a MutableState object. You’ll use the mutableStateOf() function to create an object of MutableState.
var memberName = mutableStateOf("")
There’s a problem. When you hover over the squiggly line, you’ll see that Android Studio is reminding you to store the state using the remember function so that it isn’t lost during recomposition.
Now, you’ll update the code to store state using the remember function:
var memberName by remember { mutableStateOf("") }
Make sure you include the following imports:
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
Build and run the project.
When you enter a new member’s name, the name now shows on the screen.