鸿蒙开发中的用户首选项(用来存储轻量级数据)
·
用户首选项

用户首选项是用来长期存储用户轻量级数据
第一步:
在ets文件下创建common目录,common目录用来存放components(用来存放组件)目录和util(工具)目录。
其中的util目录就是用来存放用户首选项文件的。
第二步:
util目录下创建PreferencesUtil.est文件,如下:
import preferences from '@ohos.data.preferences'
class PreferencesUtil {
// 创建一个Map类型用来存储pref的name,和pref
prefMap: Map<string, preferences.Preferences> = new Map()
// 加载Preferences
async localPreferences(context: Context, name: string) {
// 获取pref,返回的是一个Promise
let pref = await preferences.getPreferences(context, name)
// 将Pref填入PrefMap中
this.prefMap.set(name, pref)
}
// 放Preferences数据
async putPreferencesValue(name: string, key: string, value: preferences.ValueType) {
// 从Map中获取pref
let pref = this.prefMap.get(name)
// 在pref中添加
await pref?.put(key, value)
// 将pref输入磁盘中
await pref?.flush()
}
// 读Preferences数据
async getPreferencesValue(name: string, key: string, defaultValue: preferences.ValueType) {
// 从map中获取pref
let pref = this.prefMap.get(name)
return await pref?.get(key, defaultValue)
}
}
const preferencesUtil = new PreferencesUtil()
export default preferencesUtil as PreferencesUtil
第三步:
在entryability目录中的EntryAbility.est文件中添加:
// 这个是在创建Ability就会执行
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
//添加如下代码
PreferencesUtil.localPreferences(this.context,'gao')
}
第四步:
在index中使用:
import PreferencesUtil from '../common/util/PreferencesUtil'
@Entry
@Component
struct Index {
@State s: number = 100
async aboutToAppear() {
this.s = await PreferencesUtil.getPreferencesValue('gao', 'w', 100) as number
}
build() {
Column() {
Image($r('app.media.startIcon'))
.width(this.s)
Row() {
Button('点击变大')
.onClick(() => {
PreferencesUtil.putPreferencesValue('gao', 'w', this.s += 50)
})
Button('点击变小')
.onClick(() => {
PreferencesUtil.putPreferencesValue('gao', 'w', this.s -= 50)
})
Text(`宽是:${this.s}`)
}
}
}
}
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐



所有评论(0)