has anyone implemented dark theme in jetpack compo...
# compose
m
has anyone implemented dark theme in jetpack compose using datastore? I mean the settings should be persistent
In this approach everything is working fine, but since the value is null initially it shows the system theme mode for a second
z
What Ive done for a situation like this is to defer rendering the content until the theme has been loaded, and in the period before have a theme defined in androidManifest that mirrors the device theme (DayNight variants, etc). That will still show a change if your device is set to dark, and the app theme is light; but for all other cases it looks really neat.
j
Is it possible send the value from Activity level if Android? Then you can wait setContent until loaded. Another variant would be use splash screen or empty state while theme is null.
j
Here's what I do: 1. Create an injectable class:
class AppPreferences(context: Context)
. 2. You can use this library with datastore to make things easier for use and future testing as well. This an example of how it is used with datastore. 3. Now that you have your preferences class setup, define a theme preference in it. 4. Inject the
Apppreferences
into your
MainActivity
and pass the instance to when you will call your theme composable.
Copy code
@Inject
lateinit var appPreferences: AppPreferences
...
setContent {
   YourAppsTheme(appPreferences) { ... } 
}
1. Inside your theme, use the app preferences to get theme preference. If you are using the suggested lib, it should be very easy:
Copy code
@Composable
fun YourAppsTheme(appPreferences: AppPreferences) {
    val theme by appPreferences.theme.getFlow().collectAsState()
    // Use theme however you want!
}
m
Thank you so much guys, for helping me out