Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get false as initial state Datastore in Jetpack Compose?

How to get false as initial state Datastore in Jetpack Compose? I would initial state be false. I changed it to false in CollectAsState() but it always return true.

class DataStoreUtil(private val context: Context) {

    companion object {
        private val Context.dataStore: DataStore<androidx.datastore.preferences.core.Preferences> by preferencesDataStore("settings")
        val FORCE_DARK_THEME = booleanPreferencesKey("force_dark_theme")

    }

    val getForceDarkTheme: Flow<Boolean> = context.dataStore.data
        .map { preferences ->
            preferences[FORCE_DARK_THEME] ?: true
        }

    suspend fun saveForceDarkTheme(value: Boolean) {
        context.dataStore.edit { preferences ->
            preferences[FORCE_DARK_THEME] = value
        }
    }
}

@Composable
fun MySwitch() {
    val scope = rememberCoroutineScope()
    val dataStore = DataStoreUtil(LocalContext.current)
    val switchState by dataStore.getForceDarkTheme.collectAsState(false)
   
    Switch(
        checked = switchState,
        onCheckedChange = {
            scope.launch{
                dataStore.saveForceDarkTheme(it)
            }
        }
    )
    Text(
        text = if(switchState) "foo" else "bar",
    )
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If you want to handle scenarios where there is no value present in the data store you can change to,

val getForceDarkTheme: Flow<Boolean?> = context.dataStore.data
    .map { preferences ->
        preferences[FORCE_DARK_THEME]
    }

This returns null when there is no value and you can do null check and use required logic.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading