鸿蒙学习 - 首选项 本地化 ohos.data.preferences
import preferences from '@ohos.data.preferences';
import common from '@ohos.app.ability.common';
import hilog from '@ohos.hilog';
// 封装的首选项的工具类
class PreferenceUtils {
// 以后各个页面需要用这个单例
shareInstance: preferences.Preferences = null
// 程序入口初始化首选项:
getInstance(content: common.Context) {
try {
preferences.getPreferences(content, "kXMStore", (err, value) => {
if (err) {
hilog.debug(0x01, "xiaoming", err.message);
} else {
this.shareInstance = value
}
})
} catch (err) {
hilog.debug(0x01, "xiaoming", "getPreferences失败catch:%s",err.message);
}
}
}
export default new PreferenceUtils()
/*
使用案例:
*
// 获取首选项值
PreferenceUtils.shareInstance.get("kIsDarkStyle", false).then(res => {
this.isDarkStyle = res as boolean
})
// 或者
async aboutToAppear() {
// 获取首选项值
this.isDarkStyle = await PreferenceUtils.shareInstance.get("kIsDarkStyle", false) as boolean
}
// 更新首选项值:
Toggle({type:ToggleType.Switch, isOn: this.isDarkStyle}).onChange(async value => {
this.isDarkStyle = value
// 更新首选项值
await PreferenceUtils.shareInstance.put("kIsDarkStyle", value)
await PreferenceUtils.shareInstance.flush()
})
*/