Search code examples
kotlinkeyrefreshitemslazycolumn

LazyColumn items key not responding to my code in Kotlin


I am making a change in my List in the LazyColumn and added a key to the items property expecting to refresh the LazyColumn with the new List. But the LazyColumn does not refresh.

What do you suggest?

I have the following code segments:

class colNames(
val name:String,
val id:String
)

var colparent:List<colNames> = emptyList<colNames>()

//Process filling the List
var tempList: MutableList<colNames>
//Some code
colparent = tempList.toList()

LazyColumn(modifier = Modifier.padding(top = 36.dp)) 
{
itemsIndexed(
 items = colparent,
 key = { _, item -> item.id },
) { ind, item ->
    Text(
         text = item.name,
         modifier = Modifier
              .clickable(
                 onClick = {colparent = reorderNamesList(colparent, ind)} //This is a test function that changes the item position in the list ramdomly by the index
               )
    )
  }
}

Solution

  • I found the solution for my question.

    I had:

    var colparent by remember { mutableStateOf<List<colNames>>(emptyList<colNames>()) }
    

    Then change to:

    var colparent:List<colNames> = emptyList<colNames>()
    

    Neither work. Finally I found an article: "Exploring Jetpack Compose LazyList animations" with a full example and notice that the problem was that I needed a MutableStateList no just a MutableState.

    The final code is:

    val listItems = remember { colparent.toMutableStateList() }  //THIS IS THE KEY                      
                                                   
    LazyColumn(modifier = Modifier.padding(top = 36.dp)) 
    {
       itemsIndexed(
            items = listItems ,
            key = { _, item -> item.id },
       ) { ind, item ->
           Text(
                text = item.name,
                modifier = Modifier
                   .clickable(
                      onClick = {
                         colparent = reorderNamesList(colparent, ind) 
                         //Above is a test function that changes the item position 
                         //in the list ramdomly by the index
                         colparent.forEachIndexed { id, x -> listItems[id] = x } 
                         //This is part of the solution. 
                         //Now Modify listItems, since is a State List the LacyColumn key statement 
                         //detects the State change thus the LazyColumn refreshes.
                      } 
                   )
           )
        }
    }