I'm referring to the example in https://developer.android.com/jetpack/compose/state. When I code
var expanded by remember { mutableStateOf(false) }
It errors stating
Type 'TypeVariable(T)' has no method 'getValue(Nothing?, KProperty<*>)' and thus it cannot serve as a delegate
The below works though
val expanded = remember { mutableStateOf(false) } // OR val (expanded, setExpanded) = remember { mutableStateOf(false) }
Note: remember stores objects in the Composition, and forgets the object when the composable that called remember is removed from the Composition. mutableStateOf creates an observable MutableState<T> , which is an observable type integrated with the compose runtime.
State is to MutableState as List is to MutableList. An extension function on State<T> that allows instances to act as property delegates for read-only properties (vals), via the by syntax. An extension function on MutableState<T> that allows instances to act as property delegates for mutable properties (vars).
By using mutableStateOf we allow mutating the randomFruit value which causes recomposition of Composable scope (s) that use it (Button content lambda, in this case) Note that now our Button text changes when clicked (given that current random value is different from previous one).
There are three ways to declare a MutableState object in a composable: These declarations are equivalent, and are provided as syntax sugar for different uses of state. You should pick the one that produces the easiest-to-read code in the composable you're writing.
Apparently, I have to include these imports
import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue
The auto imports don't automatically recommend it in the beta Android Studio 4.2
If you use livedata, then consider the below import
import androidx.compose.runtime.livedata.observeAsState
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With