Reputation: 373
Why is my list not updating? I spent the whole day yesterday, debugging this and researching but I couldn't find anything to help me. I have a companion object in my fragment, which is initially an empty mutableList:
class MainTillLayoutFragment : Fragment() {
companion object {
var mBasket = mutableListOf<Product?>()
}
...
}
I have a method called addToBasket. which gets a "Product" item as a parameter and it adds it to the mBasket:
private fun addToBasket(product: Product) {
mBasket.add(product)
println("PRODUCTS ADDED NEW BASKET IS $mBasket")
}
And then I have a composable function that uses mBasket in the items() function to loop through each of the products and display a Text in each row of the lazyColumn:
LazyColumn(
modifier = Modifier
.background(color = Color.Red)
.fillMaxSize(),
content = {
items(mBasket) {
if (it != null) {
Text(text = it.name)
}
}
}
)
The data DOES get updated HOWEVER the UI does NOT, anything wrong with the code above that I should try guys?
Thanks in advance everyone :)
Upvotes: 9
Views: 7626
Reputation: 373
I FOUND THE FIX If anybody ever needs it, instead of using mutableListOf<>(), try using mutableStateListOf<>(), which should keep track of the STATE and recompose the view automatically for you!!
In my case instead of
var mBasket = mutableListOf<Product?>()
I should have done
var mBasket = mutableStateListOf<Product?>()
Upvotes: 25