I am new to compose and have written some Compose ...
# compose
p
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
Do you mean with add/remove animations?
p
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
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
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
@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
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
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
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
@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.