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

robnik

12/13/2020, 3:31 AM
I know there is a bug where
LazyColumnFor
does not remember things when items are removed and shifted. I heard that
key(...)
provides a workaround. I tried this, but it didn't work:
Copy code
LazyColumnFor(items = nums) { listNum ->
   key(listNum) {
      val r = remember { Random.nextInt(300) }
      Text("Num: $listNum, remembered: $r")
   }
}
nums
is mutable state. When I remove the first item, all the remembered numbers change.
a

Andrey Kulikov

12/13/2020, 3:28 PM
yes, it is not yet supported but in progress. once it is done you will be able to provide your keys for elements which would help to move the state of the item together with the item
c

Colton Idle

12/13/2020, 4:56 PM
Interesting. I always thought that you would have to just lift the state out of the lazy composable.
j

jim

12/13/2020, 5:35 PM
Yeah, or you could do that too, that would also work.
Hoisting state out of your lazy composables has a few other advantages. For instance, you can restore that state if/when the item ever returns because the user scrolled back up.
c

Colton Idle

12/13/2020, 5:41 PM
Interesting. Seems like keys for elements would let people shoot themselves in the foot in a way... no? I haven't used compose enough to even really have an opinion here. I'm just thinking about the canonical android interview question that I'm always asked. Create a RV with a list of names and a checkbox next to every name. Seems like the state of whether or not a person is checked should belong to an application and not the view.
👆 1
💯 1
Got a 100 and a point up from Jim? Made my month! 😅
j

JulianK

01/11/2021, 9:38 AM
For checkboxes, this may be true. But what about swipable items in a list that reveal additional buttons (delete)? I'd argue that the revealState is something that may belong to the view. For those cases, key() in LazyColumn would be good to have...
2 Views