The following Jetpack Compose code attempts to dynamically change the text color based on the theme. What's the problem, and how would you fix it?
Android interview question for Advanced practice.
Answer
The isSystemInDarkTheme() function is called only once, and doesn't update when the system theme changes. The textColor should be derived from MaterialTheme.colors.
Explanation
The problem is that isSystemInDarkTheme() is only called once, and the composable doesn't recompose when the system theme changes. To fix it, you should use MaterialTheme's color system: kotlin @Composable fun MyTextComposable(text: String) { val textColor = MaterialTheme.colors.onSurface Text(text = text, color = textColor) } This way, the textColor will automatically update whenever the theme changes, ensuring that your UI reflects the current theme correctly.