简体   繁体   English

如何从 DataStore Preferences 读取字符串?

[英]How to read from DataStore Preferences to string?

Im trying to use datastore inside Composable to read user data but cant read the value as string to put inside Text.我试图使用 Composable 中的数据存储来读取用户数据,但无法将值作为字符串读取以放入 Text 中。 That's the datastore那是数据存储

private val Context.userPreferencesDataStore: DataStore<Preferences> by preferencesDataStore(
  name = "user"
)
private val USER_FIRST_NAME = stringPreferencesKey("user_first_name")
suspend fun saveUserToPreferencesStore(context: Context) {
  context.userPreferencesDataStore.edit { preferences ->
    preferences[USER_FIRST_NAME] = "user1"
  }
}
fun getUserFromPreferencesStore(context: Context): Flow<String> = context.userPreferencesDataStore.data
  .map { preferences ->
    preferences[USER_FIRST_NAME] ?: ""
  }

and inside Composable:和内部可组合:

@Composable
fun myComposable() {
  var context = LocalContext.current
  LaunchedEffect( true){
    saveUserToPreferencesStore(context )
  
  }
  Text(getUserFromPreferencesStore(context ))
}

so in your code, getUserFromPreferencesStore() is returning a Flow.所以在你的代码中, getUserFromPreferencesStore()返回一个流。 so you should collect that as flow, and then compose will auto update once the data is being changed.因此,您应该将其收集为流,然后一旦数据发生更改,撰写将自动更新。 For example (something similar to this):例如(类似于此):

val user by getUserFromPreferencesStore(context).collectAsStateWithLifecycleAware(initValue)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM