简体   繁体   中英

UI List not updating jetpack compose with mutableList but data updates

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

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?>()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM