Why my Jetpack Compose Text does not recomposed while TextField does

621 Views Asked by At

In Android Jetpack Compose app, I have tried a clickable update on Text.

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent { ColorBox() }
    }
}

@Composable
fun ColorBox() {
    val zero = 0
    val full = 255
    var r by remember { mutableStateOf(zero) }
    var g by remember { mutableStateOf(full) }
    var b by remember { mutableStateOf(zero) }
    val color = Color(r,g,b)
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(color)
            .clickable {
                val until = 256
                r = Random.nextInt(until)
                g = Random.nextInt(until)
                b = Random.nextInt(until)
            },
        contentAlignment = Alignment.Center,
    ) {
        Column {
            Text(text = "R:$r, G:$g, B:$b")
            TextField(value = "R:$r, G:$g, B:$b", onValueChange = {})
        }
    }
}

When I click on the screen, the background color changes. I expect both Text and TextField change with respect to the color RGB components. But Text didn't change while TextField changed as expected, as shown in the image below.

after click, the color changed but Text does not update

Doesn't Text Composable run recomposition, and why does not?

1

There are 1 best solutions below

0
On BEST ANSWER

The problem was version dependency of UI, thanks @Halifax.

Project: build.gradle:

buildscript {
    ext {
//        compose_ui_version = '1.1.1'
        compose_ui_version = '1.3.3'  // -- (*)
    }
}

Module: build.gradle:

dependencies {
//    implementation 'androidx.compose.material:material:1.1.1'  // -- (*)
    implementation 'androidx.compose.material:material:1.3.1'
}

The version combination marked // -- (*) causes the above problem.