How to correctly store a list in a mutablestate re...
# compose
p
How to correctly store a list in a mutablestate remember variable? I tried with
val imagesList by remember *{* _mutableStateListOf_<ImageModel>()*}*
but it gives this error
Type 'TypeVariable(T)' has no method 'getValue(Nothing?, KProperty<*>)' and thus it cannot serve as a delegate
If I replace
by remember
with
= remember
the error dissapears and I dont understand why. Also, the guides says
by remember
is the correct option so I whould like to understand how to be able to use
by remember
with this list. Another problem I found is that even using
=
instead of
by
, I'm not able to init the variable with a list.
remember *{* _mutableStateListOf_<ImageModel>(ImageModelProvider.imageModelList)*}*
gives this error:
Type mismatch. Required: ImageModel Found:List<ImageModel>
e
with
MutableState
, you can either destructure it to a getter and setter, or operate with its
.value
getter and
.setValue()
setter, or use
var by
delegation to handle that for you
with
SnapshotStateList
(returned from
mutableStateListOf()
), you simply use `.get()`/`.set()` (e.g.
[]
indexing operators) as normal. so it's
=
it's not a
MutableState<List>
, it's a
MutableList
that allows Compose to observe changes
p
Well I'm exactly in the same point than before. Maybe can you show me a working sample for initialize that list correctly with by remember and those initial values?
e
what you have written is basically the same as writing `mutableListOf(imageModelList)`; it is a list of a single list, not a list of its elements. to convert a list to a mutable state list, you use the conversion function
Copy code
val imagesList = remember { ImageModelProvider.imageModelList.toMutableStateList() }
p
so it is not allowed to use by here, must be used =
z
If your ViewModel is the source of truth and you’re getting a new list from your view model when it changes, store the list in a mutableStateOf and just put the new list in there every time you get a new one. If the list you’re creating in the remember is the source of truth, use mutableStateListOf and then you can mutate the list directly without having to create a whole new list every time. (You can technically use this approach if your VM is the source of truth too but there’s no advantage, you’d have to clear then addAll every time.)
1112 Views