Home > Software engineering >  Lazycolumn does not update when deleting an item
Lazycolumn does not update when deleting an item

Time:10-21

I am trying to delete an item from Lazycolumn. Here is my code :

MyViewModel.kt :

class MyViewModel:ViewModel() {

    val items = MutableLiveData<List<Items>>()

    fun removeItem(item: Items) {
        items.value = items.value?.filter { it != item }?.toList()
    }

MainActivity.kt :

class MainActivity : ComponentActivity() {
    @ExperimentalFoundationApi
    @SuppressLint("UnusedMaterialScaffoldPaddingParameter")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val viewmodel = ViewModelProvider(this).get(MyViewModel::class.java)
        setContent {
            JetPackAppTheme {

 val list = Mylist()
            val getData = list.getData()
                viewmodel.items.value=getData

  LazyColumn(
                        verticalArrangement = Arrangement.spacedBy(12.dp),
                        contentPadding = PaddingValues(all=16.dp),


                        ) {

                        items(items = viewmodel.items.value!!) { item->
                            CustomItem(item = item,
                                onItemClick = {
                                    viewmodel.removeItem(it)
                                    
                                }
}

}

}

}

The problem is that the LazyColumn does not update , but items in the MyViewModel class update.

CodePudding user response:

Use SnapshotStateList instead of a MutableList if you want your composable to update on list changes

class MyViewModel:ViewModel() {

    val items = MutableLiveData<SnapshotStateList<Items>>()

    fun removeItem(item: Items) {
        items.value?.remove(item)
    }
}

You can create an instance of a SnapshotStateList the same way you instantiate an ordinary list.

val stateList = mutableStateListOf<Item>(...)

You also don't need a LiveData in your example here, just create an instance of SnapshotStateList

class MyViewModel:ViewModel() {

    val items = mutableStateListOf( <your items here> )

    fun removeItem(item: Items) {
        items.value?.remove(item)
    }
}

and simply reference it from your composable

LazyColumn {
       items(items = viewmodel.items) { item->
             CustomItem(item = item,
                 onItemClick = {
                    viewmodel.removeItem(it)
                 }
        }
}

Have a look at this similar post Jetpack Compose: LazyColumn not updating with MutableList

  • Related