kotlindatastore

Unresolved reference: preferencesKey Android Kotlin


I'm trying to store boolean in DataStore.

class OnboardingPrefs(val context: Context) {

    companion object {
        const val ON_BOARDING_PREFS = "on_boarding_prefs"
        const val ONBOARD_KEY = "onBoard"

    }

    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
        name = ON_BOARDING_PREFS
    )

    suspend fun saveOnboarding(save: Boolean) {
        context.dataStore.edit { preferences ->
            preferences[preferencesKey<Boolean>(ONBOARD_KEY)] = save
        }
    }
}

Problem is preferencesKey cannot be resolved.

Gradle:

implementation 'androidx.datastore:datastore-preferences:1.0.0'


Solution

  • There is no preferencesKey. You can use booleanPreferencesKey instead.

    import androidx.datastore.preferences.core.booleanPreferencesKey
    
    suspend fun saveOnboarding(save: Boolean) {
        context.dataStore.edit { preferences ->
            preferences[booleanPreferencesKey(ONBOARD_KEY)] = save
        }
    }