创建preferences
//加载
async loadPreference(context: Context, name: string) {
try {
this.pref = await preferences.getPreferences(context, name)
console.log("xzjTest", "加载成功")
} catch (err) {
console.log("xzjTest", `获取失败:${err}`)
}
}
因为首选项的创建取值以及存储都是异步过程,所以需要加上await和async,还需要导入首选项的包
import preferences from '@ohos.data.preferences'```
//存值
async putValue(key: string, value: preferences.ValueType) {
try {
await this.pref?.put(key, value)
await this.pref?.flush()
console.log("xzjTest", `存储成功,,value:${JSON.stringify(value)}`)
} catch (e) {
console.log("xzjTest", `获取失败:${e}`)
}
}```
//取值
async getValue(key: string, value: preferences.ValueType) {
try {
console.log("xzjTest", `获取成功,value:${value}`)
return await this.pref?.get(key, value)
} catch (e) {
console.log("xzjTest", `获取失败:${e}`)
}
return value
}
}
//使用的时候在程序入口EntryAbility中的onCreate方法中初始化
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
PreferenceUtil.loadPreference(this.context, "list")
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
}
页面中使用
取值
async aboutToAppear() {
this.getList()
this.finishedTask = await PreferenceUtil.getValue("finishedTask", 0) as number
this.totalTask = await PreferenceUtil.getValue("totalTask", 0) as number
}
存值
handTaskChange() {
this.totalTask = this.taskList.length
this.finishedTask = this.taskList.filter(i => i.finished).length
PreferenceUtil.putValue("totalTask", this.totalTask)
PreferenceUtil.putValue("finishedTask", this.finishedTask)
PreferenceUtil.putValue("list", this.taskList)
}