Home > database >  How to use my datastore prefrence in fragment kotlin
How to use my datastore prefrence in fragment kotlin

Time:05-25

private val Context.dataStore by preferencesDataStore("app_preferences")

I want to use the datastore above but the variable cannot be read or used in the fragment. like this picture enter image description here

CodePudding user response:

To read from a preferences dataStore, you must use the corresponding key type function to define a key for each value that you need to store in the DataStore instance. For example, to define a key for an int value, use intPreferencesKey(). Then, use the DataStore.data property to expose the appropriate stored value using a Flow:

val EXAMPLE_COUNTER = intPreferencesKey("example_counter")
val exampleCounterFlow: Flow<Int> = context.dataStore.data
  .map { preferences ->
    // No type safety.
    preferences[EXAMPLE_COUNTER] ?: 0
}

for more information refer to the documentation: https://developer.android.com/topic/libraries/architecture/datastore

CodePudding user response:

To get dataStore reference in Fragment

private val Context.dataStore by preferencesDataStore("app_preferences")


// in Fragment
val pref = requireContext().dataStore
  • Related