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

pajatopmr

07/18/2022, 3:46 PM
I am new to compose and have written some Compose code using the Jetsnack sample code as a guide. One of the things that Jetsnack does not provide guidance for is how to dynamically add or remove items to scrollable lists. While I am trying to understand what to “remember” about a a list using videos, articles and Android documentation, a link to a sample app, code-lab or tutorial that illustrates adding or removing items to a list would be much appreciated.
z

Zach Klippenstein (he/him) [MOD]

07/18/2022, 3:53 PM
Do you mean with add/remove animations?
p

pajatopmr

07/18/2022, 3:56 PM
No, but if the material that helps me understand how to add or remove list items also explains animation at the same time, that would be very cool.
f

Filip Wiesner

07/18/2022, 3:56 PM
In declarative UI frameworks you don't add or remove parts of UI. You just declare them or don't declare them. For example consider this
Copy code
LazyColumn {
    item { Text("Item1") }
    item { Text("Item2") }
}
Here you "remove" Item 2 by just not declaring it. This can be done for example with boolean flag.
Copy code
LazyColumn {
    item { Text("Item1") }
    
    if (item2Displayed) {
        item { Text("Item2") }
    }
}
(This flag would have to be a
State
so the UI gets updated on change)
z

Zach Klippenstein (he/him) [MOD]

07/18/2022, 3:58 PM
If your UI is backed by a list data structure, you either need to use an implementation of that data structure that is snapshot aware (eg
mutableStateListOf()
) or to store an immutable list in one (eg
mutableStateOf()
). In both those cases, when you add/remove from those lists, your compose ui should automatically update
p

pajatopmr

07/18/2022, 4:00 PM
@Filip Wiesner I do not think your answer is my case, which is more like `items { ... }`where one of the items is removed by tapping the element and selecting remove.
f

Filip Wiesner

07/18/2022, 4:02 PM
In that case Zachs answer is more helpful 🙂
I was just describing the general idea of why you don't "just remove" a part of UI in declarative UI framework
p

pajatopmr

07/18/2022, 5:25 PM
Yes, Zach’s answer looks to be in the ballpark … now I just need to grok it. Where “grok” means see it used in the wild. :-)
t

Tobias Suchalla

07/19/2022, 5:35 AM
Maybe the
todoapp-lite
example may help: https://github.com/JetBrains/compose-jb/tree/master/examples/todoapp-lite/common/src/commonMain/kotlin/example/todoapp/lite/common Take a look at
RootStore
. It holds the list (wrapped in
RootState
) and provides methods to edit and remove items. Both are then used in
MainContent
(via
RootContent
).
p

pajatopmr

07/22/2022, 6:38 PM
@Tobias Suchalla thanks for the suggestion. Checking it out now….
Just to wrap up this thread, my problem was not fully understanding that all elements of a list must be “remembered”, not just changes to the list.
3 Views