Easy and Scalable Solution.
If you have limited variables then answer of @tyg (link) is enough.
My solution handles scalability, if you have 1000+ variables? and also type Text() composable inside column 1000+ times? No.
It is based on Observable Lists i.e MutableStateList (official codelab by google check) and lazy column instead of simple column.
Simple steps:
get all data into list
convert it into MutableStateList using list.toMutableStateList() extension
show lazycolumn using this MutableStateList items
update it based on it's indexes on buttonclick
**
100% working code:**
@Preview(showBackground = true)
@Composable
fun MinimalMutableStateComposable(modifier: Modifier = Modifier) {
val dataList = getMyData() //first get complete data
val mutableDataListState =
remember { dataList.toMutableStateList() } //and then turn it into state_list, don't build MutableStateList item by item here to avoid weird recompositions
LazyColumn(modifier = modifier.padding(16.dp)) {
items(mutableDataListState) {
Text(text = it.toString())
}
item {
Button(
onClick = {
mutableDataListState[0] = 100 //updating 0th value, you can update any value at index
}
) {
Text("Change some value")
}
}
}
}
//method that returns you data which can be any length
fun getMyData(): List<Int> =
listOf(1, 2, 3, 4, 5, 6) // which is a,b,c,d,e,f,g change this data
@Preview
@Composable
fun PreviewMinimalMutableStateComposable() {
MinimalMutableStateComposable()
}
If you want to change every value and need buttons for every item then you will use some Row which groups Text and Button and use itemsIndexed instead items inside lazycolumn, somewhat like below:
itemsIndexed(mutableDataListState) { index, value ->
ItemRowTextWithButton(
index = index,
value = value,
onUpdate = { i -> mutableDataListState[i] = value + 1 } //lambda to update
)
}