You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Kotlin中如何为Preference DataStore设置初始值

给Preference DataStore设置初始值的两种实用方案

针对你的需求,这里提供两种简单可行的实现方式,分别适配不同场景:


方案一:读取时返回默认值(推荐,无需提前写入存储)

这种方式不会将默认值持久化到DataStore,仅在读取时判断,若存储中无对应值则返回预设的默认值,适合默认值可能随版本迭代调整的场景。

修改你的SettingsRepository代码如下:

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

    // 定义各设置项的默认值映射
    private val defaultSettings = mapOf(
        WIND_SPEED_UNIT to "km/h",
        VISIBILITY_UNIT to "km",
        PRESSURE_UNIT to "hPa",
        TEMPERATURE_UNIT to "°C"
    )

    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 preferences[dataStoreKey] ?: defaultSettings[settingKey] ?: ""
    }

    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"
    }
}

方案二:初始化DataStore时写入默认值

这种方式会在应用首次启动时,将默认值直接写入DataStore持久化存储,适合需要默认值固定不变的场景。

修改后的代码如下:

class SettingsRepository {
    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
        name = "user_settings",
        // 初始化阶段写入默认值
        initializer = {
            mutablePreferencesOf(
                stringPreferencesKey(WIND_SPEED_UNIT) to "km/h",
                stringPreferencesKey(VISIBILITY_UNIT) to "km",
                stringPreferencesKey(PRESSURE_UNIT) to "hPa",
                stringPreferencesKey(TEMPERATURE_UNIT) to "°C"
            )
        }
    )

    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 preferences[dataStoreKey] ?: ""
    }

    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"
    }
}

两种方案对比

  • 方案一:无需修改存储内容,默认值可随版本灵活调整,用户未主动修改的设置会自动同步新默认值。
  • 方案二:默认值持久化存储,后续即使代码中默认值变更,用户未修改的设置仍保留首次初始化的值。

内容的提问来源于stack exchange,提问作者HaBuiDuc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 20:22:23