# compose

Md Sohail

03/08/2024, 10:19 AM
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

Zoltan Demant

03/08/2024, 1:01 PM
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.

Joel Denke

03/08/2024, 1:14 PM
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.

Jasjeet Singh

03/08/2024, 2:36 PM
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
into your
and pass the instance to when you will call your theme composable.
Copy code
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
fun YourAppsTheme(appPreferences: AppPreferences) {
    val theme by appPreferences.theme.getFlow().collectAsState()
    // Use theme however you want!

Md Sohail

03/09/2024, 9:59 AM
Thank you so much guys, for helping me out