when i have a ```State<List<MyData>>``...
# compose-desktop
n
when i have a
Copy code
State<List<MyData>>
how would i use a layout compontn like Rowm Column or smth else to render each element in the list ? essentially, can i do a renderEach ?
z
Unless you know the list will always be very small, the safest bet is to use
LazyColumn
or
LazyRow
But technically yes, you could just iterate over it with a foreach and call other composables. That’s not as performant as using the lazy list composables though.
t
Try
LazyColumn
as @Zach Klippenstein (he/him) [MOD] mentioned
Copy code
LazyColumn {
    items(myList.value) { item ->
        Text("Item : $item")
    }
}
n
so this will re-render the items if myList.value changes ? nice
z
if
List
is either immutable and you push a new value into the
State
, or if your list is a
mutableStateListOf
, then yes
1
If your list is simply a
mutableListOf
, and you mutate the list, it won’t trigger recompositions
n
okay so either list in state or mutableStateListOf, makes sense
👍 1
t
Copy code
fun main() {

    val myList = mutableStateListOf(
        MyData("A"),
        MyData("B"),
        MyData("C"),
    )

    Window {

        Column {
            LazyColumn {
                items(myList.size) { itemIndex ->
                    val item = myList[itemIndex]
                    Text("Item : ${item.name}")
                }
            }

            Button(
                onClick = {
                    myList.add(MyData("NEW: ${Date()}"))
                }
            ) {
                Text(text = "Add New Item")
            }
        }

    }
}
n
i tried this.. but it seems to crash as soon as the list reduces in size it seems to re-render and cannot find the index anymore PS i guess i need
myList.getOrNull(ItemIndex) ?: return@items
a
known issue fixed by https://android-review.googlesource.com/c/platform/frameworks/support/+/1640311 - this should be in beta03 next week
n
heh, nice
well this about scrolling.. in my case i have a TextField and a remembered TextFieldValue on each element and when i remove any element.. only the last element in the rendered lsit gets removed.. (although console tells me the data is correct) i do the remembered TextFieldValue this way:
Copy code
val textState = remember(index) { mutableStateOf(TextFieldValue(item.foo)) }
i hope this makes sense.. i am new to this and jsut want to see what i can do
i found a way to make it work i guess, use
State<MyData>
as elements in the list and do not use
remember {}
at all