I'm working on a shopping cart feature for my app. I'm looking to add/decrease quantity of each list item in LazyColumn individually. I'm using only one "remember" so if I click on add/decrease they all update at the same time. How do I control each Item individually?
@Composable
fun InventoryCartScreen(
mainViewModel: MainViewModel = hiltViewModel()
) {
val multiSelectValue = mutableStateOf(0)// This is the value I want to change
//random list
val shopList = listOf(
ShoppingList(id = 0,itemNumber = "1",itemDescription = "1",currentInventory = 0,optimalInventory = 0,minInventory = 0),
ShoppingList(id = 0,itemNumber = "2",itemDescription = "2",currentInventory = 0,optimalInventory = 0,minInventory = 0)
)
Column(...) {
LazyColumn(...) {
items(items = shopList, key = { it.id }) { item ->
InventoryCartScreenContents(
onaddClick= { multiSelectValue.value ++ }, //adds for all
onDecreaseClick = { multiSelectValue.value -- }, //decreases for all
value = multiSelectValue.value //setting the initial value for all
)
}
}
}
}
Below is the contents composable to help you reproduce the issue.
@Composable
fun InventoryCartScreenContents(
onAddClick: (Int) -> Unit,
onDecreaseClick: () -> Unit,
value: Int,
) {
Row(...) {
Button(
onClick = { onAddClick(itemId) }
) {
Text(text = "+")
}
Button(
onClick = onDecreaseClick
) {
Text(text = "-")
}
}
}
Create a
mutableStateListOf(...)
(ormutableStateOf(listOf(...))
object if the former does not support your data type) in yourViewModel
. Now, access this state from the composable you wish to read it from, i.e., yourLazyColumn
.Inside your
ViewModel
, you can set the values however you wish, and they will be updated in the Composable as and when they are updated. Now, the composable, i.e., you column could use the index of the list item as the index of the lazycolumn's item. So you can store different data for different items in the viewmodel and it'll work fine.The problem seems to be that you are missing the concept of state-hoisting here. I thought I had some good posts explaining it but it seems this one's the best I've posted. Anyway, I recommend checking this official reference, since that's where I basically found that (with a little bit of headhunting, so to speak.)
The basic idea is that everything is stored in the viewModel. Then, you divide that state into "setters" and "getters" and pass them down the heirarchy.
For example, the ViewModel may have a item called
text
, ok?If you wish to update the value of
text
on the click of a button, this is how you will hook up that button with the viewModelIn your Button Composable declaration
This button reads the value 'get' from the viewModel, i.e., it reads the value of
text
, as it is passed down the model to the composable. Then, when we receive a click event from the button (in theonClick
), we invoke the setter that we received as a parameter to the Composable, and we invoke it with a new value, in this case "Updated Text", this will go upwards all the way to the viewModel, and change the value oftext
in there.Now,
text
was originally initialized as a state-holder, by usingmutableStateOf(...)
in initialization, which will trigger recompositions upon its value being changed. Now, since the value actually did change (from "Initial Text" to "Updated Text"), recompositions will be triggered on all the Composables which read the value of thetext
variable. Now, ourComposeButton
Composable does indeed read the value oftext
, since we are directly passing it to thegetter
parameter of that Composable, that right? Hence, all of this will result in a Composable, that will read a value from a single point in the heirarchy (the viewmodel), and only update when that value changes. The Viewmodel, therefore, acts as a single source of truth for the Composable(s).What you'll get when you run this is a Composable that reads "Initial Text" at first, but when you click it, it changes to "Updated Text". We are connecting the Composables to the main viewModel with the help of getters and setters. When Composables receive events, we invoke setters we receive from the models, and those setters continue the chain up to the viewModel, and change the value of the variables (state-holder) inside the model. Then, the Composables are already reading those variables through 'getters', hence, they recompose to reflect the updated value. This is what state-hoisting is. All the state is stored in the viewModel, and is passed down to the Composables. When a value needs to change, the Composables pass 'events' up to the viewModel (up the heirarchy), and then upon the updating of the value, the updated state is passed down to the Composables ('state' flows down the heirarchy).
All you need, is to use this method, but with a list. You can keep track of the items by using their index, and update their properties in the viewModel like this example demonstrates updating the value of
a
. You can store all the properties of an item in a single list.Just create a data-class, like so
Then,
val list by mutableStateOf(listOf<Item>())
Clear?
Ok here is the explanation SPECIFIC to your use-case.
Your code seems excessively large but here's what I got down:
You have two items in a lazycolumn, both of them have three buttons each. Your question is about two buttons, increase and decrease. You wish to have the buttons modify the properties of only the item they belong to, right?
Ok so again, use state-hoisting as explained above
Getters and Setters being created, you will use them to read and update ENTIRE ITEMS, even if you have to modify a single property of them. We can use convenience methods like
copy()
to make our lives easier here.Just create a data class and store everything in there. The class
Item
(not the Composable) I've demonstrated is the data-class. It could have a value like soNow, in your
Item
Composable, where you receive the 'add' event (in theonClick
of the 'Add' Button), just update the value using the setter like thisJust do the same for decrease and delete (
updateItem(0)
), and you should have accomplished this well... Finally. If you have any more doubts, just ask. I could assist over facetime if nothing works.