How to switch between light and dark theme dynamically in app using composables
At the moment I don't have any Idea why your code not works, I'll update this answer when I find out.
but instead of using if
else
for colors
parameter use it for the whole MaterialTheme like this and it will work:
@Composable
fun MyAppTheme(
children: @Composable() () -> Unit
) {
if (ThemeState.isLight) {
MaterialTheme(colors = themeColorsLight) {
children()
}
} else {
MaterialTheme(colors = themColorDark) {
children()
}
}
}
Update: seems that it's bug in Jetpack Compose dev11, I tried in dev12 and it works there.
NOTE 1:
@Model
has been deprecated in dev 12
change your ThemeState
to
object ThemeState {
var isLight by mutableStateOf(true)
}
more information: https://android-review.googlesource.com/c/platform/frameworks/support/+/1311293
NOTE 2
There are some problems with auto Import in recent versions of AndroidStudio
If the Idea throws error: Type 'MutableState<TypeVariable(T)>' has no method 'getValue(ThemeState, KProperty<*>)' and thus it cannot serve as a delegate
Import getValue
and SetValue
manually.
import androidx.compose.getValue
import androidx.compose.setValue
Since 0.1.0-dev16 use these imports:
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue