Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

var value by remember { mutableStateOf(default) } produce error, why?

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) } 
like image 941
Elye Avatar asked Nov 22 '20 07:11

Elye


People also ask

What is the difference between mutablestateof and remember?

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.

What is the difference between state and mutablestate in Java?

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).

What does mutablestateof do in a lambda function?

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).

How do I declare a mutablestate object in a composable?

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.


1 Answers

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 
like image 155
Elye Avatar answered Sep 28 '22 09:09

Elye