State is any value that can change over time. When the state changes, you should update the UI to reflect those changes.
You put the state in an observable value holder to track when it changes. MutableState<T> is an observable type integrated into the compose runtime. When the state changes, the observable holder notifies Compose. Then, Compose recreates the UI with the new values. You use the mutableStateOf() function to create an object of MutableState. You pass the default value to the mutableStateOf() function.
val friendsNameState: MutableState<String> = mutableStateOf("")
An object of MutableState notifies Compose when the state changes for recomposition to take place. However, it doesn’t preserve the state. The state variables will be reinitialized to their default values when recomposition occurs. You use the remember composable function to preserve the state across recompositions. The following are different ways to create an object of MutableState in a composable:
val friendsNameState = remember { mutableStateOf("") }
var friendsName by remember { mutableStateOf("") }
You’ll use the remember and mutableStateOf functions to store and update state for the rest of the lesson.
See forum comments
This content was released on Sep 10 2024. The official support period is 6-months
from this date.
In this lesson, you’ll learn about the MutableState interface and remember function and use them to store state and track when it changes.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.