9

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 :)

3
  • 1
    You need to use Compose's own version of state e.g. mutableStateOf....updating that then will trigger recomposition. Commented Jan 7, 2022 at 10:04
  • @JohnO'Reilly yeah i just found the answer actually! I had to use mutableStateListOf which I think is what you meant, thank you very much for your help mate! Commented Jan 7, 2022 at 10:06
  • You can also use mutableStateOf here and often that's more appropriate if the data you're interested in is already a list e.g. you might have a view model that exposes that (as perhaps flow) ....in that case you'd also perhaps use something like collectAsState to convert to state variable Commented Jan 7, 2022 at 10:08

1 Answer 1

26

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?>()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.