https://kotlinlang.org logo
Title
n

Nikky

03/18/2021, 7:18 PM
when i have a
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

Zach Klippenstein (he/him) [MOD]

03/18/2021, 7:23 PM
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

theapache64

03/18/2021, 7:24 PM
Try
LazyColumn
as @Zach Klippenstein (he/him) [MOD] mentioned
LazyColumn {
    items(myList.value) { item ->
        Text("Item : $item")
    }
}
n

Nikky

03/18/2021, 7:27 PM
so this will re-render the items if myList.value changes ? nice
z

Zach Klippenstein (he/him) [MOD]

03/18/2021, 7:27 PM
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

Nikky

03/18/2021, 7:28 PM
okay so either list in state or mutableStateListOf, makes sense
👍 1
t

theapache64

03/18/2021, 7:32 PM
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

Nikky

03/18/2021, 8:15 PM
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

Adam Powell

03/18/2021, 8:25 PM
known issue fixed by https://android-review.googlesource.com/c/platform/frameworks/support/+/1640311 - this should be in beta03 next week
n

Nikky

03/18/2021, 8:25 PM
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:
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