https://kotlinlang.org logo
#compose
Title
# compose
d

dimsuz

09/01/2020, 12:11 PM
I must miss something obvious, but why
Copy code
var inputState: TextFieldValue by mutableStateOf(TextFieldValue())
fails with an error
Copy code
Type 'MutableState<TypeVariable(T)>' has no method 'getValue(Nothing?, KProperty<*>)' and thus it cannot serve as a delegate
f

flosch

09/01/2020, 12:12 PM
Either
var inputState: TextFieldValue = mutableStateOf(TextFieldValue())
or
var inputState: TextFieldValue by remember { mutableStateOf(TextFieldValue()) }
d

dimsuz

09/01/2020, 12:13 PM
both give the similar error 😞
d

Daniel Sandström

09/01/2020, 12:14 PM
You need to import
Copy code
androidx.compose.runtime.getValue
androidx.compose.runtime.setValue
👍 2
d

dimsuz

09/01/2020, 12:15 PM
great this worked, thanks! What is the difference between using delegate and "remember"?
f

flosch

09/01/2020, 12:15 PM
delegation and
remember
cannot be compared.
remember
can be called by delegation (`getValue`/`setValue`),
mutableStateOf
cannot.
Sorry scratch that,
mutableStateOf
, can be called by delegation
d

dimsuz

09/01/2020, 12:21 PM
hmm. I can see this in the codelab:
Copy code
var todoItems: List<TodoItem> by mutableStateOf(listOf())
no remember and delegation. But it doesn't work when I try to feed TextFieldValue like this
Only using
by remember { mutableStateOf(...) }
works
f

flosch

09/01/2020, 12:23 PM
You should read through the code-lab to find out what
remember { X }
,
mutableStateOf(X)
and
remember { mutableStateOf(X) }
are doing.
d

dimsuz

09/01/2020, 12:24 PM
They cause recomposition If value changes I guess. But I'm not sure I understand what's the point of
by mutableStateOf
then
will read this codelab in full then 🙂
f

flosch

09/01/2020, 12:25 PM
You can read about delegated properties here. This is a kotlin thing, not a compose thing.
d

dimsuz

09/01/2020, 12:29 PM
If
by mutableStateOf
simply adjusts property to delegate to state's get/set, then I don't understand why codelab's examples work without remember:
Copy code
var todoItems: List<TodoItem> by mutableStateOf(listOf())
propagates changes to composables. While if I do this with
TextFieldValue
it isn't propagating. only if I additionaly wrap in
remember
— then it does.
2 Views