Reputation: 527
I have a list of files in a LazyColumn. User can select multiple files in the list. I have a button floating over that list. The text of the button is "Archive n files" (where n is the number of selected files in the list) I want the text of the button to change every time a file is selcted or unselected in the list.
I use a MutableState<MutableList> that containt the selected files
selections = rememberSaveable { mutableStateOf(mutableListOf()) }
When a user clic on a file in the displayed list, I add or remove an entry in selections
if (row.isSelectedState.value) {
selections.value.add(row.idConversation)
} else {
selections.value.remove(row.idConversation)
}
The size of selections
is used in the button text
text =
if (selections.value.size == 0)
"Archive"
else
String.format("Archive %1$d conversations", selections.value.size)
The problem is that when we add or remove items in selections
the text of the button doesn't change, the recomposition is not trigerred base on selections.value.size
I fixed this by using another state
selectionCount = rememberSaveable { mutableStateOf(selections.value.size) }
text =
if (selectionCount.value == 0)
"Archive"
else
String.format("Archive %1$d conversations", selectionCount.value)
And update this state every time I add or remove an item in selections
if (row.isSelectedState.value) {
selections.value.add(row.idConversation)
} else {
selections.value.remove(row.idConversation)
}
selectionCount.value = selections.value.size
But I don't like this solution because I have to maintain another state and can forget to update it in futur code where we add or remove items in selections
What can I do for the recomposition of the button to be triggered after adding/removing items in selections
?
Upvotes: 1
Views: 1809
Reputation: 1240
replace this:
selections = rememberSaveable { mutableStateOf(mutableListOf()) }
with this:
selections = rememberSaveable { mutableStateListOf<Selection>()}
Here is good explanation of difference between mutableStateListOf
and mutableStateOf
Upvotes: 2
Reputation: 1012
Create the selection list as
val selections = remember { mutableStateListOf<Selection>()}
Create a variable to save the size
var size = 0
LaunchedUnit(key=selections.size){
size = selections.size
}
this LaunchedEffect block will execute everytime selections.size changes, use the size variable wherever you would like to display it.
Upvotes: 0