如何在 android Kotlin 中将初始值放入首选项数据存储中

问题描述 投票:0回答:1

我想将用户设置保存到首选项数据存储中。

这是我的代码

class SettingsRepository {
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "user_settings")

suspend fun saveSetting(context: Context, data: String, settingKey: String) {
    val dataStoreKey = stringPreferencesKey(settingKey)
    context.dataStore.edit { settings ->
        settings[dataStoreKey] = data
    }
}

suspend fun getSetting(context: Context, settingKey: String): String? {
    val dataStoreKey = stringPreferencesKey(settingKey)
    val preferences = context.dataStore.data.first()
    return if (preferences[dataStoreKey] != null) {
        preferences[dataStoreKey]
    } else {
        null
    }
}

companion object {
    const val WIND_SPEED_UNIT = "wind_sp_unit"
    const val VISIBILITY_UNIT = "visibility_unit"
    const val PRESSURE_UNIT = "pressure_unit"
    const val TEMPERATURE_UNIT = "temperature_unit"
}

}

我不知道如何为首选项数据存储设置初始值。我希望我的应用程序在用户第一次启动时使用默认设置。例如,我希望默认的风速单位是公里/小时,如果用户想要更改单位,则会存储新值。

我期待任何意见或建议。谢谢你

android kotlin sharedpreferences
1个回答
0
投票

一个超级简单且可用于生产的方法是对代码进行小修改:

return if (preferences[dataStoreKey] != null) {
    preferences[dataStoreKey]
} else {
    preferencesDefaults[dataStoreKey] // previous: null
}

然后定义上面的默认映射:

val preferencesDefaults = mapOf(“windSpeed” to "15", “humidity” to "31.4", “userName” to "Bob”)

保存新的自定义值后,数据库中的单个值将不再为空,并且默认值将被忽略。要检查是否使用默认值,您可以使用一个函数来检查键是否为空。要动态初始化此地图可以来自后端并且每个区域都不同。

一个好处是你的函数永远不会返回 null!

© www.soinside.com 2019 - 2024. All rights reserved.