Hi, Hoping someone can help me with TextField, Out...
# compose
d
Hi, Hoping someone can help me with TextField, OutputTransformation and derivedState. I have defined an OutputTransformation for my BasicTextField. The transformation is based on other state. How do I link the state of the BasicTextField to the other state so that a recomposition occurs - and thus the OutputTransformation is refreshed, when the other state changes? thanks
s
Providing some code of what you've tried so far would most likely be very helpful.
d
I think I fixed it...seems that the other state, wasn't actually part of the state. My silly. making it part of the state does cause a recompose. I would kind of prefer it not to be, but then I would have to "refresh" the TextField which is not the compose way of thinking.
The actual code is more complex than this, but if your interested this kind of captures it.
Copy code
var color = Color.Green

        singleWindowApplication(
            title = "Test",
        ) {
            val regex = Regex("error")
            val textState by remember { mutableStateOf(TextFieldState("this text contains error and other things.")) }
            val outputTransformation = OutputTransformation({
                val txt = this.originalText
                if(txt.isNotEmpty()) {
                    val annotated = buildAnnotatedString {
                        regex.findAll(txt).forEach {
                            addStyle(SpanStyle(color), it.range.start, it.range.endInclusive+1)
                        }
                    }
                    setComposition(0, txt.length, annotated.annotations)
                    changeTracker.trackChange(0, txt.length, txt.length)
                }
            })

            Surface {
                Column {
                    Row {
                        Button(onClick = { color = Color.Red }) { Text("Red") }
                        Button(onClick = { color = Color.Blue }) { Text("Blue") }
                    }
                    BasicTextField(
                        cursorBrush = SolidColor(MaterialTheme.colorScheme.onSurface),
                        textStyle = TextStyle(color = MaterialTheme.colorScheme.onSurface),
                        state = textState,
                        modifier = Modifier
                            .fillMaxSize(),
                        outputTransformation = outputTransformation
                    )
                }
            }
        }
moving variable color into a remembered mutableState fixes the issue.
s
Ah yes. Compose otherwise has no way to be notified about the fact that color has changed. So it won't recompose, so nothing will change. You can make color a mutableState out there, top level and it should still work btw.