How can I start recomposition in my buttons? As far as I understand something in the list itself needs to be changed, how can I go about this?
data class KeyData(var text: String, val size: Int, var colour: Color)
val firstRowKeyboard = listOf("Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P")
.map { text: String -> KeyData(text, 35, Color.White) }.toMutableStateList()
// I tried both ways, but nothing changes
val secondRowKeyboard = "ASDFGHJKL".toCharArray()
.map { text: Char -> KeyData(text.toString(), 35, Color.White) }.toMutableStateList()
and the trigger:
fun checkKeyboard() {
for (i in 0..9){
val letter = firstRowKeyboard[i]
if (letter.text in yellowLetterList){
firstRowKeyboard[i] = letter.copy(colour = Color.Yellow)
}
}
}
and my composables:
@Composable
fun Keyboard() {
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
viewModel.firstRowKeyboard.forEach {
MyKeyboardButton(it.text, it.size, it.colour)
}
}
}
@Composable
fun MyKeyboardButton(text: String, width: Int, colour: Color) {
val buttonColour by remember {
mutableStateOf(colour)
}
Button(
onClick = {
viewModel.addLettersToGrid(text)
},
modifier = Modifier
.width(width.dp)
.height(60.dp)
.padding(0.dp, 2.dp),
colors = ButtonDefaults.buttonColors(backgroundColor = buttonColour),
border = BorderStroke(2.dp, Color.LightGray)
) {
Text(text = text, textAlign = TextAlign.Center)
}
}
the colour is changing in the list, so something is working, however recomposition is never triggered.
If the colour of the KeyData changing isnt enough then would I need to change the text within the list? What is a good alternative?
CodePudding user response:
You are not setting
val buttonColour by remember {
mutableStateOf(colour)
}
other than composition.
Thera re few options you can take
First one is not that good but it will still work
val buttonColour by remember {
mutableStateOf(colour)
}
buttonColour = colour
or
val buttonColour by remember(colour) {
mutableStateOf(colour)
}
And better option is to remove
val buttonColour by remember(colour) {
mutableStateOf(colour)
}
from KeyboardButton
@Composable
fun MyKeyboardButton(text: String, width: Int, colour: Color) {
Button(
onClick = {
viewModel.addLettersToGrid(text)
},
modifier = Modifier
.width(width.dp)
.height(60.dp)
.padding(0.dp, 2.dp),
colors = ButtonDefaults.buttonColors(backgroundColor = colour),
border = BorderStroke(2.dp, Color.LightGray)
) {
Text(text = text, textAlign = TextAlign.Center)
}
}
and change it to a stateless Composable since you pass color from ViewModel.